Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 361277d

Browse files
add q40
1 parent a898a5e commit 361277d

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@
101101

102102
* [q10_正则表达式匹配](/src/回溯法/q10_正则表达式匹配)
103103
* [q22_括号生成](/src/回溯法/q22_括号生成)
104+
* [q40_组合总和2](/src/回溯法/q40_组合总和2)
104105
* [q46_全排列](/src/回溯法/q46_全排列)
105106

106107
### 树的遍历
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package 回溯法.q40_组合总和2;
2+
3+
import java.util.*;
4+
5+
/**
6+
* 回溯法 O(n*log(n))
7+
*/
8+
class Solution {
9+
10+
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
11+
List<List<Integer>> res = new ArrayList<>();
12+
if (candidates.length == 0) {
13+
return res;
14+
}
15+
Arrays.sort(candidates);
16+
helper(candidates, target, 0, new LinkedList<>(), res);
17+
return res;
18+
}
19+
20+
public void helper(int[] candidates, int target, int start, LinkedList<Integer> stack, List<List<Integer>> res) {
21+
if (start > candidates.length) {
22+
return;
23+
}
24+
if (target == 0 && !stack.isEmpty()) {
25+
List<Integer> item = new ArrayList<>(stack);
26+
res.add(item);
27+
}
28+
HashSet<Integer> set = new HashSet<>();
29+
for (int i = start; i < candidates.length; ++i) {
30+
if (!set.contains(candidates[i]) && target >= candidates[i]) {
31+
stack.push(candidates[i]);
32+
helper(candidates, target - candidates[i], i + 1, stack, res);
33+
stack.pop();
34+
set.add(candidates[i]);
35+
}
36+
}
37+
}
38+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /