Ecommet

Combination Sum

Medium Problem 88 of 151 Java and Python

Problem

Given an array of distinct integers candidates and a target, return all unique combinations of candidates that sum to target. The same number may be used any number of times.

Two combinations are the same if they use each number the same number of times. Return them in any order.

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]]

Example 3

Input
candidates = [2], target = 1
Output
[]

Constraints

  • 1 ≤ candidates.length ≤ 30
  • 2 ≤ candidates[i] ≤ 40, all distinct
  • 1 ≤ target ≤ 40

Explanation

Build combinations in non-decreasing index order so each multiset is produced once. After choosing candidates[i], recurse with the same i (it can be reused), and never go back to earlier indexes.

Sorting lets you stop the loop as soon as a candidate exceeds what is left of the target.

Approach 1 · Naive

Try any order, deduplicate

  • Time Exponential, much worse than the ordered version
  • Space O(target) recursion plus the set

At each step try every candidate, which produces the same combination in many orders; sort each result and keep unique ones in a set.

  1. search(remaining): if 0, record the sorted path in a set.
  2. For every candidate ≤ remaining: push, recurse, pop.
Java
import java.util.*;

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Set<List<Integer>> found = new HashSet<>();
        search(candidates, target, new ArrayList<>(), found);
        return new ArrayList<>(found);
    }

    private void search(int[] candidates, int remaining, List<Integer> path, Set<List<Integer>> found) {
        if (remaining == 0) {
            List<Integer> combo = new ArrayList<>(path);
            Collections.sort(combo);
            found.add(combo);
            return;
        }
        for (int c : candidates) {
            if (c <= remaining) {
                path.add(c);
                search(candidates, remaining - c, path, found);
                path.remove(path.size() - 1);
            }
        }
    }
}
Python
class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        found, path = set(), []

        def search(remaining):
            if remaining == 0:
                found.add(tuple(sorted(path)))
                return
            for c in candidates:
                if c <= remaining:
                    path.append(c)
                    search(remaining - c)
                    path.pop()

        search(target)
        return [list(c) for c in found]

Approach 2 · Optimal

Backtracking from a start index

  • Time O(n^(T/m)), T = target, m = smallest candidate (exponential)
  • Space O(T/m) recursion

Sort the candidates. From index start, try each candidate that still fits, and recurse with the same index so it can repeat.

  1. Sort candidates.
  2. backtrack(start, remaining): if remaining == 0, record path.
  3. For i from start: if candidates[i] > remaining, break. Push, recurse with (i, remaining - candidates[i]), pop.
Java
import java.util.*;

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> result = new ArrayList<>();
        backtrack(candidates, 0, target, new ArrayList<>(), result);
        return result;
    }

    private void backtrack(int[] candidates, int start, int remaining, List<Integer> path, List<List<Integer>> result) {
        if (remaining == 0) {
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = start; i < candidates.length && candidates[i] <= remaining; i++) {
            path.add(candidates[i]);
            backtrack(candidates, i, remaining - candidates[i], path, result);
            path.remove(path.size() - 1);
        }
    }
}
Python
class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        candidates = sorted(candidates)
        result, path = [], []

        def backtrack(start, remaining):
            if remaining == 0:
                result.append(path[:])
                return
            for i in range(start, len(candidates)):
                if candidates[i] > remaining:
                    break
                path.append(candidates[i])
                backtrack(i, remaining - candidates[i])
                path.pop()

        backtrack(0, target)
        return result

Complexity compared

ApproachTimeSpace
Naive Try any order, deduplicateExponential, much worse than the ordered versionO(target) recursion plus the set
Optimal Backtracking from a start indexO(n^(T/m)), T = target, m = smallest candidate (exponential)O(T/m) recursion

Key takeaways

  • Recurse with i to allow reuse, i + 1 to use each element once (Combination Sum II).
  • Sorting enables the break, which prunes whole branches.

Your notes

Saved in this browser as you type.

Solved it on your own?

Mark it done to track your progress, or star it to come back before an interview.

Next problem