-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathCombinationSumII.java
More file actions
76 lines (63 loc) · 2.35 KB
/
CombinationSumII.java
File metadata and controls
76 lines (63 loc) · 2.35 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
/**
* LeetCode 40 https://leetcode.com/problems/combination-sum-ii/
*/
// Rely on startIndex to avoid duplicate case
class Solution {
List<List<Integer>> res = new LinkedList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
backtrack(candidates, target, 0, 0);
return res;
}
void backtrack(int[] candidates, int target, int sum, int startIndex) {
// base case
if (sum == target) {
res.add(new LinkedList(path));
return;
}
for (int i = startIndex; i < candidates.length && sum + candidates[i] <= target; i++) { // prune
// duplicate case
if (i > startIndex && candidates[i] == candidates[i-1]) {
continue;
}
sum += candidates[i];
path.add(candidates[i]);
backtrack(candidates, target, sum, i + 1);
path.removeLast();
sum -= candidates[i];
}
}
}
// Rely on boolean[] used to avoid duplicate case
class Solution {
List<List<Integer>> res = new LinkedList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
boolean[] used = new boolean[candidates.length];
Arrays.sort(candidates);
backtrack(candidates, target, used, 0, 0);
return res;
}
void backtrack(int[] candidates, int target, boolean[] used, int sum, int startIndex) {
// base case
if (sum == target) {
res.add(new LinkedList(path));
return;
}
for (int i = startIndex; i < candidates.length && sum + candidates[i] <= target; i++) {
// duplicate case
// !!!! Mistakes were made here by missing i > 0 and caused ArrayIndexOutOfRange Exception
if (i > 0 && candidates[i] == candidates[i-1] && used[i-1] == false) { // prune
continue;
}
sum += candidates[i];
path.add(candidates[i]);
used[i] = true;
backtrack(candidates, target, used, sum, i + 1);
used[i] = false;
path.removeLast();
sum -= candidates[i];
}
}
}