๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“š Study Note/LeetCode

216. Combination Sum III

by Jellll_y 2022. 11. 24.

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 through 9 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