-
Notifications
You must be signed in to change notification settings - Fork 2
/
Combination-Sum-II.java
44 lines (33 loc) · 1.03 KB
/
Combination-Sum-II.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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// User function Template for Java
class Solution {
List<List<Integer>> res;
List<Integer> cur;
public List<List<Integer>> CombinationSum2(int arr[], int n, int k) {
res = new ArrayList<>();
cur = new ArrayList<>();
Arrays.sort(arr);
dfs(arr, 0 , k);
return res;
}
void dfs(int arr[], int idx, int k){
// Base case 1
if(k == 0){
res.add(new ArrayList<>(cur));
return;
}
// Base case 2
if(idx == arr.length || k < 0){
return;
}
for(int i = idx; i < arr.length; i++){
if(i > idx && arr[i] == arr[i - 1]){
continue;
}
cur.add(arr[i]);
// Recursive Call
dfs(arr, i + 1, k - arr[i]);
// Backtracking : remove last value
cur.remove(cur.size() - 1);
}
}
}