Skip to content

Commit be3bf77

Browse files
add CombinationSum and test
1 parent c691b31 commit be3bf77

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.thealgorithms.backtracking;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.List;
6+
7+
/** Backtracking: pick/not-pick with reuse of candidates. */
8+
public class CombinationSum {
9+
10+
public static List<List<Integer>> combinationSum(int[] candidates, int target) {
11+
Arrays.sort(candidates); // helps pruning
12+
List<List<Integer>> res = new ArrayList<>();
13+
backtrack(candidates, target, 0, new ArrayList<>(), res);
14+
return res;
15+
// Note: result order is not guaranteed; compare sorted in tests if needed
16+
}
17+
18+
private static void backtrack(int[] nums, int remain, int start, List<Integer> path, List<List<Integer>> res) {
19+
if (remain == 0) {
20+
res.add(new ArrayList<>(path));
21+
return;
22+
}
23+
for (int i = start; i < nums.length; i++) {
24+
int val = nums[i];
25+
if (val > remain) break; // prune
26+
path.add(val);
27+
backtrack(nums, remain - val, i, path, res); // i (reuse allowed)
28+
path.remove(path.size() - 1);
29+
}
30+
}
31+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.thealgorithms.backtracking;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import java.util.ArrayList;
6+
import java.util.Comparator;
7+
import java.util.List;
8+
import org.junit.jupiter.api.Test;
9+
10+
class CombinationSumTest {
11+
12+
private static List<List<Integer>> norm(List<List<Integer>> x) {
13+
List<List<Integer>> y = new ArrayList<>();
14+
for (var p : x) {
15+
var q = new ArrayList<>(p);
16+
q.sort(Integer::compare);
17+
y.add(q);
18+
}
19+
y.sort(Comparator.<List<Integer>, Integer>comparing(List::size)
20+
.thenComparing(a -> a.toString()));
21+
return y;
22+
}
23+
24+
@Test
25+
void sample() {
26+
int[] candidates = {2,3,6,7};
27+
int target = 7;
28+
var expected = List.of(List.of(2,2,3), List.of(7));
29+
assertEquals(norm(expected), norm(CombinationSum.combinationSum(candidates, target)));
30+
}
31+
}

0 commit comments

Comments
 (0)