Skip to content

Commit 8eb6001

Browse files
committed
CombinationSumII.java added
1 parent dd0e942 commit 8eb6001

File tree

3 files changed

+113
-35
lines changed

3 files changed

+113
-35
lines changed

.idea/workspace.xml

Lines changed: 46 additions & 35 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pom.xml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,12 @@
2727
<artifactId>rxjava</artifactId>
2828
<version>3.1.8</version>
2929
</dependency>
30+
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
31+
<dependency>
32+
<groupId>org.slf4j</groupId>
33+
<artifactId>slf4j-api</artifactId>
34+
<version>2.0.16</version>
35+
</dependency>
3036
</dependencies>
3137
<build>
3238
<plugins>
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package com.thealgorithm.backtracking;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.List;
6+
7+
/**
8+
* @author: Subham Santra
9+
*/
10+
public class CombinationSumII {
11+
static class Solution {
12+
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
13+
List<List<Integer>> result = new ArrayList<>();
14+
15+
Arrays.sort(candidates);
16+
helper(candidates, 0, 0, target, result, new ArrayList<>());
17+
18+
return result;
19+
}
20+
21+
void helper(
22+
final int[] arr,
23+
final int i,
24+
final int sum,
25+
final int target,
26+
final List<List<Integer>> result,
27+
final List<Integer> currentSet) {
28+
29+
if (sum > target) {
30+
return;
31+
}
32+
33+
if (sum == target) {
34+
result.add(new ArrayList<>(currentSet));
35+
return;
36+
}
37+
38+
if (i == arr.length) {
39+
return;
40+
}
41+
42+
// include
43+
currentSet.addLast(arr[i]);
44+
helper(arr, i + 1, sum + arr[i], target, result, currentSet);
45+
currentSet.removeLast();
46+
47+
// exclude : not only the current index also all the indexes having same value
48+
// This is required because we want to remove the duplicate set
49+
// 1 2 2 2 2 2 5
50+
// When we have found {1, 2[1], 2[2]} we shall not add {1, 2[1], 2[3]} ... etc.
51+
int j = i;
52+
while (j < arr.length && arr[j] == arr[i]) ++j;
53+
helper(arr, j, sum, target, result, currentSet);
54+
}
55+
}
56+
57+
public static void main(String[] args) {
58+
System.out.println(new Solution().combinationSum2(new int[] {2, 5, 2, 1, 2}, 5));
59+
System.out.println(new Solution().combinationSum2(new int[] {2, 2, 2, 2, 2, 2, 4, 4, 4, 4, 8, 7, 1, 1}, 8));
60+
}
61+
}

0 commit comments

Comments
 (0)