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.
Ensure that numbers within the set are sorted in ascending order.
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]]
[思路]
因为k是不定的, 所以无法用LOOP. 递归是此类题的常用解法. 为了方便, 多用一个variable: sum保存当前cur中所有数的和. 注意要新建一个list 放入结果中, 否则放入的reference 会指向原来的不断变化的list, res.add(new ArrayList(cur));
[CODE]
class Solution { public: void visit(int pos, int k, int n, int &sum, vector<int> &buf, vector<vector<int> > &result) { if (k == 0) { if (sum == n) { result.push_back(buf); } return; } for (int i = pos; i <= 9; i++) { if (sum + i > n) { break; } buf.push_back(i); sum += i; visit(i+1, k-1, n, sum, buf, result); buf.pop_back(); sum -= i; } } vector<vector<int>> combinationSum3(int k, int n) { vector<vector<int> > result; vector<int> buf; int sum = 0; visit(1, k, n, sum, buf, result); return result; } };