1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
| class Solution {
vector<vector<int>> result;
public:
/*
* ## 解题思路
* * 回溯法
*/
vector<vector<int>> combinationSum3(int k, int n) {
vector<int> nums = {1,2,3,4,5,6,7,8,9};
vector<int> tmp;
dfs(nums, tmp, n, k, 0);
return result;
}
void dfs(vector<int>& nums, vector<int>& tmp, int target, int k, int s) {
if (k<0 || target < 0) {
return;
}
if(target == 0 && k==0) {
result.push_back(tmp);
return;
}
for(int i=s; i<nums.size(); i++) {
if(nums[i]>target) {
break;
}
tmp.push_back(nums[i]);
dfs(nums, tmp, target-nums[i], k-1, i+1);
tmp.pop_back();
}
}
};
|