-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0039 组合总和.cpp
More file actions
33 lines (28 loc) · 860 Bytes
/
0039 组合总和.cpp
File metadata and controls
33 lines (28 loc) · 860 Bytes
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
class Solution {
public:
vector<vector<int>> res;
vector<int> temp;
void dfs(vector<int> & candidates, int target, int idx) {
if (idx==candidates.size())
return ;
if (target==0) {
res.push_back(temp);
return ;
}
// This part must be after the previous part
if (target - candidates[idx] < 0) {
return ;
}
// do not choose candidates[idx]
dfs(candidates, target, idx+1);
// choose candidates[idx]
temp.push_back(candidates[idx]);
dfs(candidates, target-candidates[idx], idx);
temp.pop_back();
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
dfs(candidates, target, 0);
return res;
}
};