和昨天的II差不多,回溯+剪枝,判断一下个数就好
class Solution {
public:
vector<vector<int>> combinationSum3(int k, int n) {
vector<int>num = {1,2,3,4,5,6,7,8,9};
vector<vector<int>>res;
if(n < 0 || k <= 0)
{
return res;
}
vector<int>tmp;
dfs(k, n, num, 0,0, tmp, res);
return res;
}
void dfs(int k, int n, vector<int>& num, int start, int sum, vector<int>& tmp, vector<vector<int>>& res)
{
if(sum == n && tmp.size() == k)
{
res.push_back(tmp);
return;
}
if(sum > n)
{
sum = sum - tmp.front();
return;
}
for(int i = start; i < 9; i++)
{
tmp.push_back(num[i]);
dfs(k,n,num,i+1,sum+num[i],tmp,res);
tmp.pop_back();
}
}
};