-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCombinationSumOpt.java
More file actions
28 lines (24 loc) · 869 Bytes
/
CombinationSumOpt.java
File metadata and controls
28 lines (24 loc) · 869 Bytes
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
import java.util.*;
public class CombinationSumOpt {
public static void findCombinations(int ind, int[] arr, int target, List<List<Integer>> ans, List<Integer> ds) {
if (target == 0) {
ans.add(new ArrayList<>(ds));
return;
}
for (int i = ind; i < arr.length; i++) {
if (i > ind && arr[i] == arr[i - 1])
continue;
if (arr[i] > target)
break;
ds.add(arr[i]);
findCombinations(i + 1, arr, target - arr[i], ans, ds);
ds.remove(ds.size() - 1);
}
}
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> ans = new ArrayList<>();
Arrays.sort(candidates);
findCombinations(0, candidates, target, ans, new ArrayList<>());
return ans;
}
}