-
Notifications
You must be signed in to change notification settings - Fork 0
/
#0040.combination-sum-ii.cpp
38 lines (33 loc) · 1.05 KB
/
#0040.combination-sum-ii.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
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<vector<int>> result;
sort(candidates.begin(), candidates.end());
vector<int> v;
depthFirstSearch(candidates, target, 0, result, v);
return result;
}
private:
void depthFirstSearch(const vector<int>& candidates,
int target, int start,
vector<vector<int>>& result,
vector<int>& v) {
if (target == 0) {
result.push_back(v);
return;
}
int candidate;
for (int i = start; i < candidates.size(); ++i) {
candidate = candidates[i];
if (candidate > target) {
return;
}
if (i > start && candidates[i] == candidates[i - 1]) {
continue;
}
v.push_back(candidate);
depthFirstSearch(candidates, target - candidate, i + 1, result, v);
v.pop_back();
}
}
};