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]]
遇到排列组合问题,首先要想到递归
class Solution {
public:
vector<vector<int> > ret;
void helper(vector<int>& num,int n,int k,vector<int>& tmp)
{
if(n==0 && k==0)
ret.push_back(tmp);
vector<int> num_copy(num);
for(int i=0;i<num.size() && n>=num[0] && k>=0;i++)
{
tmp.push_back(num[i]);
num_copy.erase(num_copy.begin());
helper(num_copy,n-num[i],k-1,tmp);
tmp.pop_back();
}
}
vector<vector<int>> combinationSum3(int k, int n) {
vector<int> num(9,0);
vector<int> tmp;
for(int i=0;i<9;i++)
num[i]=i+1;
helper(num,n,k,tmp);
return ret;
}
};