216. Combination Sum III
Medium
Find all valid combinations of k
numbers that sum up to n
such that the following conditions are true:
- Only numbers
1
through9
are used. - Each number is used at most once.
Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order.
Example 1:
Input: k = 3, n = 7
Output: [[1,2,4]]
Explanation:
1 + 2 + 4 = 7
There are no other valid combinations.
Constraints:
2 <= k <= 9
1 <= n <= 60
์ด ๋ฌธ์ ๋ ํฉ์ด n์ด๊ณ ..! ์กฐํฉ์ ๊ธธ์ด๊ฐ k์ธ ๊ฒฝ์ฐ๋ฅผ ์ฐพ๋ ๋ฌธ์ ์ ๋๋ค.
๋ฌธ์ ํ์ด ๋ฐฉ์์ ์ด์ ๊ฒ์๋ฌผ๊ณผ ๋์ผํ๋ ์ถ๊ฐ๋ก
์กฐํฉ์ ๊ธธ์ด๊ฐ k์ ๊ฐ์์ง๋ง ์ถ๊ฐํด์ฃผ๋ฉด ๋๋ ๋ฌธ์ ์ ๋๋ค.
/**
* @param {number} k
* @param {number} n
* @return {number[][]}
*/
var combinationSum3 = function(k, n) {
const backtrack = (path, sum, start) => {
if(sum === n && path.length === k){
ans.push([...path])
return
}
for(let i=start; i<=9; i++){
if(sum + i > n) continue
path.push(i)
backtrack(path, sum+i, i+1)
path.pop()
}
}
const ans = []
backtrack([],0,1)
return ans
};
'๐ Study Note > LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
967. Numbers With Same Consecutive Differences (0) | 2022.11.26 |
---|---|
49. Group Anagrams (0) | 2022.11.26 |
39. Combination Sum (0) | 2022.11.24 |
LeetCode - Weekly Contest 296 ํ์ด ๋ฐ ํ๊ธฐ (0) | 2022.06.05 |
51. N-Queens - ๋ฐ์ผ๋ฆฌ ๋ฌธ์ (0) | 2022.06.05 |