-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproblem216.cpp
39 lines (36 loc) · 958 Bytes
/
problem216.cpp
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
33
34
35
36
37
38
39
class Solution {
public:
vector<int>nums;
int _n, _k;
vector<vector<int>>ans;
vector<int>temp;
vector<vector<int>> combinationSum3(int k, int n) {
for(int i = 1;i <= 9;i++)
nums.push_back(i);
_n = n, _k = k;
backtrack(0);
return ans;
}
void backtrack(int i){
// base case
if(i > 9)
return;
if(!_k)
{
if(!_n)ans.push_back(temp);
return;
}
// peek
if(_n - nums[i] >= 0){
_k--;
_n-=nums[i];
temp.push_back(nums[i]);
backtrack(i+1);
_k++;
_n += nums[i];
temp.pop_back();
}
// leave
backtrack(i+1);
}
};