-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathL39.cpp
35 lines (35 loc) · 959 Bytes
/
L39.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
#include <iostream>
#include <vector>
using namespace std;
class Solution{
public:
vector<vector<int>> res;
vector<int> path;
int sum = 0;
void dfs(vector<int>& candidates, int target, int startindex){
if (sum > target)
return;
if (sum == target){
res.push_back(path);
return;
}
for (int i = startindex; i < candidates.size(); i++){
path.push_back(candidates[i]);
sum += candidates[i];
dfs(candidates, target, i);// !数字可以重复选取 这里用i 不用 i + 1
sum -= candidates[i];
path.pop_back();
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target){
dfs(candidates, target, 0);
return res;
}
};
int main(){
vector<int> candidates = {2, 3, 6, 7};
int target = 7;
Solution sol;
sol.combinationSum(candidates, target);
return 0;
}