-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproblem39.cpp
40 lines (36 loc) · 872 Bytes
/
problem39.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
40
class Solution {
public:
vector<vector<int>>ans;
vector<int>temp;
int sum;
int t;
vector<int>_can;
vector<vector<int>> combinationSum(vector<int>& can, int tar) {
t = tar;
sum = 0;
_can = can;
backtrack(0);
return ans;
}
void backtrack(int i){
// base case
if(i >= _can.size() || sum > t){
return;
}
if(sum == t)
{
ans.push_back(temp);
return;
}
if(sum < t){
// peek
sum += _can[i];
temp.push_back(_can[i]);
backtrack(i);
// leave
sum -= _can[i];
temp.pop_back();
}
backtrack(i+1);
}
};