-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombinationSumll.java
More file actions
34 lines (30 loc) · 1.06 KB
/
Copy pathCombinationSumll.java
File metadata and controls
34 lines (30 loc) · 1.06 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
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> answer = new ArrayList<>();
Arrays.sort(candidates);
backtrack(answer, new ArrayList<>(), candidates, 0, target, 0);
return answer;
}
private void backtrack(List<List<Integer>> answer, List<Integer> currSet, int[] candidates, int index, int target, int curSum) {
if (curSum == target) {
answer.add(new ArrayList<>(currSet));
return;
}
else if (curSum > target) {
return;
}
for (int i = index; i < candidates.length; i++) {
if (i > index && candidates[i] == candidates[i-1]) {
continue;
}
currSet.add(candidates[i]);
curSum += candidates[i];
backtrack(answer, currSet, candidates, i+1, target, curSum);
currSet.remove(currSet.size()-1);
curSum -= candidates[i];
}
}
}