Question
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 |
|
Example 2:
Input: k = 3, n = 9
Output:
1 |
|
Analysis
这道题类似之前的Combination Sum和Combination Sum II。注意这里的题目要求,(题目好像并没有要求每个元素只能用一次,但是给出的例子是每个元素只用了一次), 所以要求: 1,同一个元素可以用1次, 2. 所求集合唯一。所以需要一个level, 每次从当前元素的下一个元素即i+1开始,对于下一次遍历从level=i开始。(如果同一个元素可以用多次,则每次从i开始,即从当前元素开始)
Solution
1 |
|
1 |
|
```