|
| 1 | +package com.thealgorithms.recursion; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +/** |
| 7 | + * This class implements the Combination Sum algorithm using recursion and backtracking. |
| 8 | + * Given an array of distinct integers candidates and a target integer target, |
| 9 | + * return a list of all unique combinations of candidates where the chosen numbers sum to target. |
| 10 | + * The same number may be chosen from candidates an unlimited number of times. |
| 11 | + * |
| 12 | + * @see <a href="https://en.wikipedia.org/wiki/Subset_sum_problem">Subset Sum Problem (Wikipedia)</a> |
| 13 | + * @see <a href="https://leetcode.com/problems/combination-sum/">Combination Sum (LeetCode)</a> |
| 14 | + * @author Tejas Rahane |
| 15 | + */ |
| 16 | +public final class CombinationSum { |
| 17 | + private CombinationSum() { |
| 18 | + } |
| 19 | + |
| 20 | + /** |
| 21 | + * Finds all unique combinations that sum to target. |
| 22 | + * |
| 23 | + * @param candidates Array of distinct integers |
| 24 | + * @param target Target sum |
| 25 | + * @return List of all unique combinations that sum to target |
| 26 | + */ |
| 27 | + public static List<List<Integer>> combinationSum(int[] candidates, int target) { |
| 28 | + List<List<Integer>> result = new ArrayList<>(); |
| 29 | + if (candidates == null || candidates.length == 0) { |
| 30 | + return result; |
| 31 | + } |
| 32 | + backtrack(candidates, target, 0, new ArrayList<>(), result); |
| 33 | + return result; |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * Backtracking helper method to find all combinations. |
| 38 | + * |
| 39 | + * @param candidates Array of distinct integers |
| 40 | + * @param target Remaining target sum |
| 41 | + * @param start Starting index for candidates |
| 42 | + * @param current Current combination being built |
| 43 | + * @param result List to store all valid combinations |
| 44 | + */ |
| 45 | + private static void backtrack(int[] candidates, int target, int start, List<Integer> current, List<List<Integer>> result) { |
| 46 | + if (target == 0) { |
| 47 | + result.add(new ArrayList<>(current)); |
| 48 | + return; |
| 49 | + } |
| 50 | + if (target < 0) { |
| 51 | + return; |
| 52 | + } |
| 53 | + |
| 54 | + for (int i = start; i < candidates.length; i++) { |
| 55 | + current.add(candidates[i]); |
| 56 | + backtrack(candidates, target - candidates[i], i, current, result); |
| 57 | + current.remove(current.size() - 1); |
| 58 | + } |
| 59 | + } |
| 60 | +} |
0 commit comments