问题描述
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]]
思考:如何回溯
递归调用,减枝
代码
class Solution {
public:
void help(int idx, int k, int n, vector<vector<int>> &ret, vector<int> &cur){
if(k <= 0){
if(k == 0 && n == 0)
ret.push_back(cur);
return;
}
for(int i = idx; i < 10; i++){
if(n - i >= 0){
cur.push_back(i);
help(i + 1,k - 1,n - i,ret,cur);
cur.pop_back();
}
else
break;
}
}
vector<vector<int>> combinationSum3(int k, int n) {
vector<vector<int>> ret;
vector<int> cur;
help(1,k,n,ret,cur);
return ret;
}
};