forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombinationSum.java
More file actions
48 lines (40 loc) · 1.66 KB
/
CombinationSum.java
File metadata and controls
48 lines (40 loc) · 1.66 KB
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
45
46
47
48
package com.thealgorithms.backtracking;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/** Backtracking: pick/not-pick with reuse of candidates. */
public final class CombinationSum {
private CombinationSum() {
throw new UnsupportedOperationException("Utility class");
}
public static List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> results = new ArrayList<>();
if (candidates == null || candidates.length == 0) {
return results;
}
// Sort to help with pruning duplicates and early termination
Arrays.sort(candidates);
backtrack(candidates, target, 0, new ArrayList<>(), results);
return results;
}
private static void backtrack(int[] candidates, int remaining, int start, List<Integer> combination, List<List<Integer>> results) {
if (remaining == 0) {
// Found valid combination; add a copy
results.add(new ArrayList<>(combination));
return;
}
for (int i = start; i < candidates.length; i++) {
int candidate = candidates[i];
// If candidate is greater than remaining target, further candidates (sorted) will also be too big
if (candidate > remaining) {
break;
}
// include candidate
combination.add(candidate);
// Because we can reuse the same element, we pass i (not i + 1)
backtrack(candidates, remaining - candidate, i, combination, results);
// backtrack: remove last
combination.remove(combination.size() - 1);
}
}
}