Skip to content

Commit c61c5f7

Browse files
authored
Create 40. Combination Sum II (#556)
2 parents 10199a1 + 34f33c3 commit c61c5f7

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

40. Combination Sum II

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution {
2+
public:
3+
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
4+
sort(candidates.begin(), candidates.end());
5+
vector<vector<int>> res;
6+
7+
vector<int> comb;
8+
dfs(candidates, target, 0, comb, res);
9+
return res;
10+
}
11+
12+
void dfs(vector<int>& candidates, int target, int start, vector<int>& comb, vector<vector<int>>& res) {
13+
if (target < 0) {
14+
return;
15+
}
16+
17+
if (target == 0) {
18+
res.push_back(comb);
19+
return;
20+
}
21+
22+
for (int i = start; i < candidates.size(); i++) {
23+
if (i > start && candidates[i] == candidates[i-1]) {
24+
continue;
25+
}
26+
27+
if (candidates[i] > target) {
28+
break;
29+
}
30+
31+
comb.push_back(candidates[i]);
32+
dfs(candidates, target - candidates[i], i + 1, comb, res);
33+
comb.pop_back();
34+
}
35+
}
36+
};

0 commit comments

Comments
 (0)