Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1b8f752

Browse files
combination-sum-ii
1 parent 4821461 commit 1b8f752

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

‎Combination-Sum-II.java‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// User function Template for Java
2+
3+
class Solution {
4+
List<List<Integer>> res;
5+
List<Integer> cur;
6+
public List<List<Integer>> CombinationSum2(int arr[], int n, int k) {
7+
res = new ArrayList<>();
8+
cur = new ArrayList<>();
9+
10+
Arrays.sort(arr);
11+
12+
dfs(arr, 0 , k);
13+
return res;
14+
}
15+
16+
void dfs(int arr[], int idx, int k){
17+
18+
// Base case 1
19+
if(k == 0){
20+
res.add(new ArrayList<>(cur));
21+
return;
22+
}
23+
24+
// Base case 2
25+
if(idx == arr.length || k < 0){
26+
return;
27+
}
28+
29+
for(int i = idx; i < arr.length; i++){
30+
if(i > idx && arr[i] == arr[i - 1]){
31+
continue;
32+
}
33+
34+
cur.add(arr[i]);
35+
36+
// Recursive Call
37+
dfs(arr, i + 1, k - arr[i]);
38+
39+
// Backtracking : remove last value
40+
cur.remove(cur.size() - 1);
41+
42+
}
43+
}
44+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /