-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCombinationSumII.java
More file actions
30 lines (29 loc) · 1.18 KB
/
CombinationSumII.java
File metadata and controls
30 lines (29 loc) · 1.18 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
public class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> combinations = new ArrayList<>();
List<Integer> possibleCombination = new ArrayList<>();
Arrays.sort(candidates);
combinationSum2(combinations, possibleCombination, candidates, target, 0);
return combinations;
}
public void combinationSum2(
List<List<Integer>> combinations,
List<Integer> possibleCombination,
int[] candidates,
int target,
int index
) {
if (target == 0) {
combinations.add(new ArrayList<>(possibleCombination));
} else if (target > 0) {
for (int i = index; i < candidates.length; ++i) {
possibleCombination.add(candidates[i]);
combinationSum2(combinations, possibleCombination, candidates, target - candidates[i], i + 1);
possibleCombination.remove(possibleCombination.size() - 1);
while (i < candidates.length - 1 && candidates[i] == candidates[i + 1]) {
++i;
}
}
}
}
}