-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.cpp
More file actions
36 lines (32 loc) · 935 Bytes
/
solution.cpp
File metadata and controls
36 lines (32 loc) · 935 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
34
35
36
#include <vector>
#include <algorithm>
using namespace std;
void backtracking(vector<int> &prefix,
int preSum,
vector<int> &candidates,
int index,
int target,
vector<vector<int>> &ret) {
if (preSum == target && !prefix.empty()) {
ret.emplace_back(prefix);
return;
}
for (int i = index; i < candidates.size(); i++) {
if (preSum + candidates[i] <= target) {
preSum += candidates[i];
prefix.push_back(candidates[i]);
backtracking(prefix, preSum, candidates, i, target, ret);
prefix.pop_back();
preSum -= candidates[i];
} else {
break;
}
}
}
vector<vector<int>> combinationSum(vector<int> &candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<vector<int>> ret;
vector<int> prefix;
backtracking(prefix, 0, candidates, 0, target, ret);
return ret;
}