Combination Sum


Combination Sum – LeetCode


Problem: Combination Sum

Problem Statement

Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target.

You may reuse the same number an unlimited number of times.

Return the combinations in any order.


Examples

Example 1
Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]

Example 2
Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]


Constraints


Intuition

This is a combinatorial generation problem. We need to explore all combinations that sum up to the target.

We use input-output recursion where:

We recurse over each element and choose to:


Input-Output Recursive Method with Backtracking

Function Signature

void findNumbers(List<List<Integer>> list, List<Integer> arr, int target, int ind, List<Integer> temp)

Parameters


Base Case

If target == 0:


Recursive Case

Loop from index ind to end:


Code (Java)

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> ans = new ArrayList<>();
        List<Integer> inAns = new ArrayList<>();

        // Remove duplicates (defensive) and sort
        Set<Integer> set = new HashSet<>();
        for (int i : candidates) set.add(i);
        List<Integer> candi = new ArrayList<>(set);
        Collections.sort(candi);

        findNumbers(ans, candi, target, 0, inAns);
        return ans;
    }

    public void findNumbers(List<List<Integer>> list, List<Integer> arr, int target, int ind, List<Integer> temp) {
        if (target == 0) {
            list.add(new ArrayList<>(temp));
            return;
        }

        for (int i = ind; i < arr.size(); i++) {
            int val = arr.get(i);
            if (target - val >= 0) {
                temp.add(val);
                findNumbers(list, arr, target - val, i, temp); // reuse same index
                temp.remove(temp.size() - 1); // backtrack
            }
        }
    }
}

Time and Space Complexity


Dry Run

Input: candidates = [2, 3], target = 5

Explore:

Answer: [[2,3]]


Conclusion

This problem is an excellent example of the input-output recursive model with backtracking, where we control combinations with repetition. It demonstrates how recursion can efficiently enumerate valid combinations under constraints.