-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCombinationSum2.java
89 lines (79 loc) · 2.93 KB
/
CombinationSum2.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package leetcode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Given a collection of candidate numbers (candidates) and a target number
* (target), find all unique combinations in candidates where the candidate
* numbers sum to target.
*
* Each number in candidates may only be used once in the combination.
*
* Note: The solution set must not contain duplicate combinations.
*/
final class CombinationSum2 {
/**
* Find all unique combinations in candidates where the candidate numbers
* sum to target.
*
* The time complexity is O(2^N) where N is the length of the candidates,
* because there are 2 choices at every iteration
*
* The space complexity is O(N) as there will be N recursive calls where N
* is the length of candidates.
*
* @param candidates The input array
* @param target The target integer
* @return The results
*/
public List<List<Integer>> combinationSum2(final int[] candidates,
final int target) {
if (candidates.length == 0 || candidates.length > 101 || target < 1
|| target > 30) {
return Collections.emptyList();
}
List<List<Integer>> result = new ArrayList<>();
// sorting allows us to stop the DFS early
Arrays.sort(candidates);
backtrack(candidates, target, result, new ArrayList<>(), 0);
return result;
}
/**
* Helper method implementing the backtracking.
*
* @param candidates The input array
* @param target The target integer
* @param result The results array containing proven candidates
* @param list The proposed candidate
* @param start The starting index for iterating over the candidates
*/
private void backtrack(final int[] candidates, final int target,
final List<List<Integer>> result, final List<Integer> list,
final int start) {
if (target < 0) {
// the candidate did not meet the conditions
return;
} else if (target == 0) {
// the candidate did meet the conditions
result.add(new ArrayList<>(list));
return;
}
for (int i = start; i < candidates.length; i++) {
// take advantage of sorting to leave early
if (candidates[i] > target) {
break;
}
// rely on sorting to avoid duplicates
if (i == start || candidates[i] != candidates[i - 1]) {
// simulate taking the number
list.add(candidates[i]);
// pass in i+1 as we can't add the current number again
backtrack(candidates, target - candidates[i], result, list,
i + 1);
// simulate not taking the number
list.remove(list.size() - 1);
}
}
}
}