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.
Note:
- All numbers will be positive integers.
- The solution set must not contain duplicate combinations.
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:
vector<vector<int>> combinationSum3(int k, int n) {
set<int> left;
for(int i = 1;i<=9;i++)
left.insert(i);
helper(vector<int>(), 0,left,k,n);
return res;
}
private:
vector<vector<int>> res;
void helper(vector<int> temp, int sum, set<int> left, int k, int n){
if(left.empty()) return;
int num = *left.begin();
set<int> left_new = left;
left_new.erase(num);
int sum_new = sum+num;
vector<int> temp_new = temp;
temp_new.push_back(num);
helper(temp, sum, left_new, k, n);
if(k == temp_new.size() && sum_new == n){
res.push_back(temp_new);
return;
}
else if(k > temp_new.size() && sum_new > n)
return;
else if(k > temp_new.size() && sum_new < n){
helper(temp_new, sum_new, left_new, k, n);
}
}
};