-
Notifications
You must be signed in to change notification settings - Fork 1
/
combination-sum-ll-1.java
30 lines (24 loc) · 1.05 KB
/
combination-sum-ll-1.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
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> results = new ArrayList<>();
Arrays.sort(candidates);
List<Integer> combination = new ArrayList<>();
findCombination(results, combination, candidates, target, 0);
return results;
}
private void findCombination(List<List<Integer>> results, List<Integer> combination, int[] candidates, int remains, int start) {
if (remains == 0) {
results.add(new ArrayList<Integer>(combination));
return;
}
for (int i = start; i < candidates.length; i++) {
if (i != start && candidates[i] == candidates[i-1])
continue;
if (remains < candidates[i])
break;
combination.add(candidates[i]);
findCombination(results, combination, candidates, remains - candidates[i], i + 1);
combination.remove(combination.size() - 1);
}
}
}