-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path39.cpp
47 lines (24 loc) · 853 Bytes
/
39.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
41
42
43
44
45
46
47
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
int index[10000];
sort(candidates.begin(), candidates.end());
backtrace(target, 0, candidates, index, 0);
return results;
}
vector<vector<int>> results;
void backtrace(int target, int sum, vector<int> &candidates, int index[], int n){
if (sum > target)
return;
if (sum == target){
vector<int> result;
for (int i=1; i <= n; i++){
result.push_back(candidates[index[i]]);
}
results.push_back(result);
return;
}
for (int i = index[n]; i < candidates.size(); i++){
index[n+1] = i;
backtrace(target, sum + candidates[i], candidates, index, n+1);
}
}