forked from Soumik-7031/SDESheet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombinationSum2Java
More file actions
23 lines (21 loc) · 812 Bytes
/
combinationSum2Java
File metadata and controls
23 lines (21 loc) · 812 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
private 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;
}
}