-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy path40. Combination Sum II
36 lines (30 loc) · 992 Bytes
/
40. Combination Sum II
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
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<vector<int>> res;
vector<int> comb;
dfs(candidates, target, 0, comb, res);
return res;
}
void dfs(vector<int>& candidates, int target, int start, vector<int>& comb, vector<vector<int>>& res) {
if (target < 0) {
return;
}
if (target == 0) {
res.push_back(comb);
return;
}
for (int i = start; i < candidates.size(); i++) {
if (i > start && candidates[i] == candidates[i-1]) {
continue;
}
if (candidates[i] > target) {
break;
}
comb.push_back(candidates[i]);
dfs(candidates, target - candidates[i], i + 1, comb, res);
comb.pop_back();
}
}
};