Skip to content

Commit e03ab27

Browse files
author
kwu130
committed
feat(src): add 40-combinationSum2
1 parent 3095702 commit e03ab27

1 file changed

Lines changed: 56 additions & 0 deletions

File tree

‎src/40-combinationSum2.cpp‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
//
2+
// Created by 1412 on 2025/10/24.
3+
//
4+
5+
#include <bits/stdc++.h>
6+
7+
using namespace std;
8+
9+
class Solution {
10+
public:
11+
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
12+
vector<vector<int>> res;
13+
ranges::sort(candidates);
14+
dfs(candidates, target, 0, {}, res);
15+
return res;
16+
}
17+
18+
private:
19+
void dfs(vector<int>& candidates, int target, int index, vector<int>&& path, vector<vector<int>>& res) {
20+
if (target == 0) {
21+
res.emplace_back(path);
22+
return;
23+
}
24+
for (int i = index; i < candidates.size(); i++) {
25+
if (candidates[i] > target) break;
26+
if (i > index && candidates[i] == candidates[i - 1]) continue; // 剪枝 重点理解这个 i>index 的作用
27+
path.emplace_back(candidates[i]);
28+
dfs(candidates, target - candidates[i], i + 1, std::move(path), res);
29+
path.pop_back();
30+
}
31+
}
32+
};
33+
34+
void test() {
35+
Solution s;
36+
vector<int> candidates = {10, 1, 2, 7, 6, 1, 5};
37+
vector<vector<int>> expected = {
38+
{1, 1, 6},
39+
{1, 2, 5},
40+
{1, 7},
41+
{2, 6}
42+
};
43+
assert(s.combinationSum2(candidates, 8) == expected);
44+
45+
candidates = {2, 5, 2, 1, 2};
46+
expected = {
47+
{1, 2, 2},
48+
{5}
49+
};
50+
assert(s.combinationSum2(candidates, 5) == expected);
51+
}
52+
53+
int main() {
54+
test();
55+
return 0;
56+
}

0 commit comments

Comments
 (0)