-
Notifications
You must be signed in to change notification settings - Fork 0
/
CombinationSumII.java
42 lines (35 loc) · 1.05 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
// https://leetcode.com/problems/combination-sum-ii/
// #array #backtracking
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> combination = new LinkedList<>();
Arrays.sort(candidates);
backtracking(0, candidates, target, result, combination);
return result;
}
private void backtracking(
int idx,
int[] candidates,
int target,
List<List<Integer>> result,
LinkedList<Integer> combination) {
if (target == 0) {
result.add(new ArrayList<Integer>(combination));
return;
}
for (int i = idx; i < candidates.length; i++) {
// duplicate
if (i > idx && candidates[i] == candidates[i - 1]) {
continue;
}
if (target >= candidates[i]) {
// forward
combination.addLast(candidates[i]);
backtracking(i + 1, candidates, target - candidates[i], result, combination);
// backward
combination.removeLast();
}
}
}
}