Combination Sum

List every group of numbers that adds up to a target, when each number may be used as often as needed.

Given an array of distinct positive integers candidates and a number target, return every combination of candidates whose sum is target. A combination is a group of numbers from the array, and the same number may appear in it any number of times. Two groups that use the same numbers the same number of times count as one, whatever their order, so each must appear only once.

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

The Idea

Picture a post office counter with an endless supply of stamps worth 2, 3, 6 and 7, and a letter that needs exactly 7 in postage. One 7 stamp does it. So do two 2 stamps and a 3 stamp. Those are the two answers of Example 1: [7] and [2, 2, 3].

Two things make this different from picking items off a shelf. A stamp value can go on the letter as often as you like, which is why 2 appears twice in [2, 2, 3]. And the order of the stamps does not matter: 2, 3, 2 and 3, 2, 2 are the same postage as 2, 2, 3. So how do we try every mix of stamps without listing the same mix in three orders?

Agree to stick the stamps on from smallest to largest. Once a 3 is on the letter, no 2 may follow it. Every mix then has one allowed order, the sorted one, so the search can meet it only once. Repeats still work, because after a 2 the next stamp may be another 2.

Look at the picture below. Each box is a group of stamps being built, with the postage still left under it. The lines between boxes are the choices, labelled take 2, take 3 and so on.

Choice tree for candidates 2, 3, 6, 7 and target 7. From the empty group with 7 left, the search takes 2, 3, 6 or 7, and [7] is an answer. Under [2] it takes 2 or 3, and [2, 2] then takes 3 to reach the answer [2, 2, 3]. Under [3] there is no take 2. Grey boxes are dead ends where the next number is more than what is left.

From the empty group [ ] with 7 left, all four values fit. Under [2], with 5 left, the search takes 2 or 3, since 6 and 7 are more than 5. Under [3] there is no take 2 line, and the orange note says why: [3, 2] would repeat [2, 3]. The two teal boxes, [7] and [2, 2, 3], reach 0 left and are the answers.

The grey boxes are dead ends. In [2, 2, 2], 1 is left and the smallest stamp allowed next is 2, so nothing fits. The search peels that last 2 off and tries the next value from [2, 2], which is 3. Sticking on one stamp at a time, and peeling off the last one to try another value when a path ends, is called backtracking. For Example 1, the whole search is the 10 boxes in the picture.

Solution Approach

Turning that idea into code means settling four things: how to grow a group one number at a time, how to let a number repeat, how to keep each group in its one sorted order, and when to stop a path early.

Growing a group one number at a time

What does one box of the picture look like in code? It is one call of a method build. The call gets the group so far in a list combo and the amount still needed in remaining. It also gets start, the index of the sorted array where its choices begin. When remaining is 0, combo is an answer.

Otherwise a loop moves an index i from start to the end of the array. For each i, it adds candidates[i] to combo, calls build to finish the group, and then removes that number again. Removing it is the peeling off of the last stamp: the next i starts from the same group as before.

Letting a number repeat

How can [2, 2, 3] take 2 twice? After adding candidates[i], the call for the next number gets i as its start, not i + 1, so the number just taken is still on offer. With i + 1, each value could be used at most once. The same code with that change returns only [[7]] for Example 1 and only [[3, 5]] for Example 2.

Keeping each group in sorted order

Why pass start at all? Without it, every call would loop over all candidates from index 0. The search would then find [2, 2, 3], [2, 3, 2] and [3, 2, 2] as three separate answers. Starting the loop at start means a call never goes back to a value smaller than the one just taken, which is the smallest-to-largest rule from the stamps.

The version without start also does more work. For Example 1 it makes 13 calls of build instead of 10 and returns 4 lists instead of 2. For Example 2 it makes 20 calls instead of 13 and returns 6 lists instead of 3.

Stopping a path early

When can a loop give up? If the candidates are sorted first, then once candidates[i] is more than remaining, every later candidate is more too. The loop ends with break instead of trying them. Each grey box in the picture is a call where this happens at the very first number it may take.

Java Solution

The method combinationSum works in these steps:

  1. First, sort the input array with Arrays.sort(candidates), so small values come first.
  2. Create the list result for the answers, and start the search with build(candidates, target, 0, new ArrayList<>(), result): an empty group, all of target still needed, and choices starting at index 0.
  3. In build, when remaining is 0, add a copy of combo to result and return. It must be a copy, since numbers keep being added to and removed from combo after this point.
  4. Otherwise, a loop moves i from start to the end of the array. It ends with break as soon as candidates[i] is more than remaining.
  5. For any other i, add candidates[i] to combo and call build with remaining - candidates[i] and i as its start. Then remove the last number from combo, so the loop can try the next value.
  6. When the first call of build returns, combinationSum returns result.

The main method runs both examples, the candidates 7, 3 and 2 given out of order, a single 1 with target 3, and a single 2 with target 1, which no group can reach.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CombinationSum {

    public static List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);                 // small values first, so we can stop early
        List<List<Integer>> result = new ArrayList<>();
        build(candidates, target, 0, new ArrayList<>(), result);
        return result;
    }

    private static void build(int[] candidates, int remaining, int start,
                              List<Integer> combo, List<List<Integer>> result) {
        if (remaining == 0) {
            result.add(new ArrayList<>(combo));  // a copy: combo keeps changing
            return;
        }
        for (int i = start; i < candidates.length; i++) {
            if (candidates[i] > remaining) {
                break;                           // this and every larger candidate is too big
            }
            combo.add(candidates[i]);
            // pass i, not i + 1: the same number may be used again
            build(candidates, remaining - candidates[i], i, combo, result);
            combo.remove(combo.size() - 1);      // take it back, try the next number
        }
    }

    public static void main(String[] args) {
        System.out.println(combinationSum(new int[] {2, 3, 6, 7}, 7));
        System.out.println(combinationSum(new int[] {2, 3, 5}, 8));
        System.out.println(combinationSum(new int[] {7, 3, 2}, 7));
        System.out.println(combinationSum(new int[] {1}, 3));
        System.out.println(combinationSum(new int[] {2}, 1));
    }
}

Running it prints:

Output
[[2, 2, 3], [7]]
[[2, 2, 2, 2], [2, 3, 3], [3, 5]]
[[2, 2, 3], [7]]
[[1, 1, 1]]
[]

Example 2 gives [[2, 2, 2, 2], [2, 3, 3], [3, 5]], and each group lists its numbers from smallest to largest, the one order the search allows. The candidates 7, 3 and 2 give [[2, 2, 3], [7]], the same as Example 1, because the sort puts them in order before the search starts.

The line [[1, 1, 1]] uses one candidate three times, which works because each call passes i on as the next start. The last line is empty: 2 is already more than the 1 needed, so the loop in the very first call of build ends with break before taking anything.

Complexity

The work is one call of build per box in a tree like the picture, and that tree grows very fast as the target grows.

  • Time: exponential, at most about nT/m + 1 calls for n candidates, target T and smallest candidate m, because a group holds at most T/m numbers and each call loops over at most n candidates.
  • Space: O(T/m) besides the output, because each number taken adds at least m to the sum, so combo and the chain of unfinished calls never hold more than T/m numbers.

When each number may be used only once and the input can repeat values, see Combination Sum II.