Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Refactor CombinationSum for better handling and clarity
Updated combinationSum method to handle null or empty candidates and improved variable naming for clarity.
  • Loading branch information
Avaneeshakrishna authored Oct 10, 2025
commit 4e1cdd273352b92116fc06b2f7e7b548f02de739
48 changes: 33 additions & 15 deletions src/main/java/com/thealgorithms/backtracking/CombinationSum.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,26 +6,44 @@

/** Backtracking: pick/not-pick with reuse of candidates. */
public 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;
}

public static List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates); // helps pruning
List<List<Integer>> res = new ArrayList<>();
backtrack(candidates, target, 0, new ArrayList<>(), res);
return res;
// Note: result order is not guaranteed; compare sorted in tests if needed
// 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[] nums, int remain, int start, List<Integer> path, List<List<Integer>> res) {
if (remain == 0) {
res.add(new ArrayList<>(path));
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 < nums.length; i++) {
int val = nums[i];
if (val > remain) break; // prune
path.add(val);
backtrack(nums, remain - val, i, path, res); // i (reuse allowed)
path.remove(path.size() - 1);

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);
}
}
}
Loading