forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCombinationSumII.java
64 lines (52 loc) · 1.97 KB
/
CombinationSumII.java
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class CombinationSumII {
// 耗时29ms
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> result = new LinkedList<>();
Arrays.sort(candidates);
helper(candidates, result, new LinkedList<>(), target, 0);
return result;
}
private void helper(int[] candidates, List<List<Integer>> result, List<Integer> list, int target, int index) {
if (target < 0) {
return;
} else if (target == 0) {
result.add(new LinkedList<>(list));
return;
} else if (index >= candidates.length) {
return;
}
list.add(candidates[index]);
helper(candidates, result, list, target - candidates[index], index + 1);
list.remove(list.size() - 1);
for ( ; index < candidates.length - 1 && candidates[index + 1] == candidates[index]; index++);
helper(candidates, result, list, target, index + 1);
}
/**
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> result = new LinkedList<List<Integer>>();
Arrays.sort(candidates);
dfs(candidates, 0, target, result, new LinkedList<Integer>());
return result;
}
private void dfs(int[] candidates, int start, int target, List<List<Integer>> result, List<Integer> path) {
if (target < 0) {
return;
}
if (target == 0) {
result.add(new LinkedList<Integer>(path));
return;
}
for (int i = start; i < candidates.length; i++) {
if (i > start && candidates[i] == candidates[i - 1]) {
continue;
}
path.add(candidates[i]);
// 关键是这里变成i + 1
dfs(candidates, i + 1, target - candidates[i], result, path);
path.remove(path.size() - 1);
}
}*/
}