|
| 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 final class CombinationSum { |
| 9 | + private CombinationSum() { |
| 10 | + throw new UnsupportedOperationException("Utility class"); |
| 11 | + } |
| 12 | + |
| 13 | + public static List<List<Integer>> combinationSum(int[] candidates, int target) { |
| 14 | + List<List<Integer>> results = new ArrayList<>(); |
| 15 | + if (candidates == null || candidates.length == 0) { |
| 16 | + return results; |
| 17 | + } |
| 18 | + |
| 19 | + // Sort to help with pruning duplicates and early termination |
| 20 | + Arrays.sort(candidates); |
| 21 | + backtrack(candidates, target, 0, new ArrayList<>(), results); |
| 22 | + return results; |
| 23 | + } |
| 24 | + |
| 25 | + private static void backtrack(int[] candidates, int remaining, int start, List<Integer> combination, List<List<Integer>> results) { |
| 26 | + if (remaining == 0) { |
| 27 | + // Found valid combination; add a copy |
| 28 | + results.add(new ArrayList<>(combination)); |
| 29 | + return; |
| 30 | + } |
| 31 | + |
| 32 | + for (int i = start; i < candidates.length; i++) { |
| 33 | + int candidate = candidates[i]; |
| 34 | + |
| 35 | + // If candidate is greater than remaining target, further candidates (sorted) will also be too big |
| 36 | + if (candidate > remaining) { |
| 37 | + break; |
| 38 | + } |
| 39 | + |
| 40 | + // include candidate |
| 41 | + combination.add(candidate); |
| 42 | + // Because we can reuse the same element, we pass i (not i + 1) |
| 43 | + backtrack(candidates, remaining - candidate, i, combination, results); |
| 44 | + // backtrack: remove last |
| 45 | + combination.remove(combination.size() - 1); |
| 46 | + } |
| 47 | + } |
| 48 | +} |
0 commit comments