[LeetCode] 216. Combination Sum III

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

Example 1:
Input: k = 3, n = 7
Output:
[[1,2,4]]

Example 2:
Input: k = 3, n = 9
Output:
[[1,2,6], [1,3,5], [2,3,4]]

從 1 - 9 個數字裡選擇 k 個數字的 和(加總) 為 n. 考慮還是用深度優先來做.

line_5: path 裡的個數為 k, 然後加總為 target 符合題目需求
line_7: res 加上 深copy. 創造新的 list 並加入到 res
line_9: 遍歷數字 1 - 9
line_10 - 12: dfs 遞歸

 

留言