40. Combination Sum II

LeetCode

Backtracking

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
class Solution {
private void util(int[] arr, int target, List<List<Integer>> res, List<Integer> ls, int start) {
if (target < 0) {
return;
} else if (target == 0) {
res.add(new ArrayList(ls));
return;
} else {
for (int i = start; i < arr.length; i++) {
if (i > start && arr[i] == arr[i - 1]){
continue;
}
ls.add(arr[i]);
util(arr, target - arr[i], res, ls, i + 1);
ls.remove(ls.size() - 1);
}
}
}

public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> res = new ArrayList<>();
util(candidates, target, res, new ArrayList<>(), 0);
return res;
}
}

0%