Combination Sum III

List every group of k different numbers from 1 to 9 whose sum is n, each group once.

Given two numbers k and n, return every combination of exactly k different numbers from 1 to 9 that add up to n. A combination is a group of numbers in which order does not matter, so [4, 1, 2] and [1, 2, 4] are the same one. Each number may be used at most once in a combination, and each combination must appear only once.

Example 1
Input: k = 3, n = 7
Output: [[1, 2, 4]]
Example 2
Input: k = 3, n = 9
Output: [[1, 2, 6], [1, 3, 5], [2, 3, 4]]
Example 3
Input: k = 4, n = 1
Output: []
Explanation: the smallest sum of four different numbers is 1 + 2 + 3 + 4 = 10.
Solution

The Idea

Picture nine tiles on a table, numbered 1 to 9. You must pick exactly three of them so that their numbers add up to 7. The tiles 1, 2 and 4 work, and no other three do, which is the answer of Example 1. There is one tile of each number, so 2, 2 and 3 is not allowed.

Raise the sum to 9, as in Example 2, and three groups work: 1, 2, 6, then 1, 3, 5, then 2, 3, 4. Each of them can also be picked in other orders, such as 6, 2, 1, yet each is listed once. So how do we find every group of tiles without listing one group twice, and without trying every possible group?

Write each group from its smallest tile to its largest. Then a group can be written in one way only, and after a tile is taken, the next tile is always a bigger one. Build the group one tile at a time and keep track of how much of the sum is still left. A path ends in two ways. When it holds three tiles, it is an answer if nothing is left. When the next tile is more than what is left, every tile after it is bigger still, so the path can stop.

Look at the picture below. It shows part of the search for Example 1. Each box is a group of tiles, with the amount still left under it, and the lines are labelled with the tile taken.

Part of the choice tree for k = 3, n = 7. From the empty group with 7 left, take 1, then 2, to get [1, 2] with 4 left. Taking 3 gives [1, 2, 3] with 1 left, a dead end. Taking 4 gives the answer [1, 2, 4]. Then 5 is more than the 4 left, so that path stops. [1, 3] with 3 left stops at once, because 4 is more than 3.

The search starts at the empty group [ ] with 7 left. It takes 1, then 2, and reaches [1, 2] with 4 left. Taking 3 gives [1, 2, 3]: three tiles, but 1 is still left, so the grey box is a dead end. Taking 4 instead gives [1, 2, 4] with 0 left, the teal answer. The next tile would be 5, and the orange box shows why the search stops there: 5 is more than the 4 left.

Then the search puts the 2 back and tries 3 as the second tile. The box [1, 3] has 3 left, and its next tile would be 4, so the second orange box stops it at once. Taking tiles one at a time, and putting the last one back when a path ends so that the next tile can be tried, is called backtracking.

Solution Approach

Turning that idea into code means settling three things: how to build a group one tile at a time, how to keep its tiles different and in increasing order, and when a path stops. Checking every possible group of tiles would also work, and comparing the two shows what the stops save.

Building a group one tile at a time

How does the code walk through the picture? A method build gets the tiles taken so far in a list combo and the amount still left in remaining. It also gets start, the smallest tile it may take next. A loop tries each tile num from start upward: it adds num to combo, calls build again for the rest of the group, then removes num again.

Each call of build is one of the blue, teal or grey boxes in the picture, and the calls it makes are the boxes under it. The orange boxes are not calls: they mark where the loop ends. Removing num is the step that puts a tile back.

Keeping the tiles different and in order

What stops a tile from being taken twice, or a group from showing up as both [1, 2, 4] and [2, 1, 4]? The call for the next tile gets num + 1 as its start. So the tiles in combo always grow from left to right, and every group is built in its one increasing order.

When a path stops

When can a call give up? At the top of build, once combo holds k tiles, the call returns. It saves a copy of combo first if remaining is 0. A group with more than k tiles can never be an answer, so there is no reason to go deeper.

The loop itself runs while num <= 9 && num <= remaining. The first part keeps the tiles inside 1 to 9. The second is the orange box of the picture: tiles only grow, so once num is more than what is left, the loop ends.

Checking every group instead

Why not look at every group of tiles and keep the right ones? Each of the nine tiles is either in a group or out of it, so there are 29 = 512 groups. For Example 2, three of them have three tiles and a sum of 9. The search with its stops calls build 33 times for Example 2 and 19 times for Example 1.

With only nine tiles, both ways stay small: 512 groups at most. The stops still matter: they keep the search off paths that cannot reach the sum, and the same pattern carries over to problems with far more choices, where checking every group would be too slow.

Java Solution

The method combinationSum3 works in these steps:

  1. First, create the list result for the answers and start the search with build(k, n, 1, new ArrayList<>(), result): no tiles taken yet, all of n still left, and 1 as the smallest tile allowed.
  2. In build, if combo already holds k tiles, add a copy of it to result when remaining is 0, and return either way. The copy is needed because combo keeps changing as the search goes on.
  3. Otherwise, a loop moves num up from start, as long as num is at most 9 and at most remaining.
  4. For each num, add it to combo and call build with remaining - num left and num + 1 as the new start. Then remove the last number from combo, so the loop can try the next tile.
  5. When the first call of build returns, combinationSum3 returns result.

The main method runs the three examples, all nine tiles with a sum of 45, and two tiles with sums of 18 and 17.

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

public class CombinationSumIII {

    public static List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> result = new ArrayList<>();
        build(k, n, 1, new ArrayList<>(), result);
        return result;
    }

    private static void build(int k, int remaining, int start,
                              List<Integer> combo, List<List<Integer>> result) {
        if (combo.size() == k) {
            if (remaining == 0) {
                result.add(new ArrayList<>(combo));  // a copy: combo keeps changing
            }
            return;                                  // k numbers chosen: stop either way
        }
        for (int num = start; num <= 9 && num <= remaining; num++) {
            combo.add(num);
            build(k, remaining - num, num + 1, combo, result);
            combo.remove(combo.size() - 1);          // take the number back
        }
    }

    public static void main(String[] args) {
        System.out.println(combinationSum3(3, 7));
        System.out.println(combinationSum3(3, 9));
        System.out.println(combinationSum3(4, 1));
        System.out.println(combinationSum3(9, 45));
        System.out.println(combinationSum3(2, 18));
        System.out.println(combinationSum3(2, 17));
    }
}

Running it prints:

Output
[[1, 2, 4]]
[[1, 2, 6], [1, 3, 5], [2, 3, 4]]
[]
[[1, 2, 3, 4, 5, 6, 7, 8, 9]]
[]
[[8, 9]]

The third line, [], is Example 3, and the search behind it is short. The first call takes 1 and leaves 0, and the next tile, 2, is already more than that, so build is called just twice. The fourth line uses every tile once, because 1 + 2 + ... + 9 is exactly 45.

The last two lines show the limit of two tiles. The largest two different tiles are 8 and 9, so 17 is the biggest sum they can reach, and [[8, 9]] is the one group for it. A sum of 18 would need 9 twice, so that line is empty.

That empty line depends on the num <= 9 part of the loop. With only num <= remaining, the loop would take numbers above 9, and two numbers with a sum of 18 would give eight groups, from [1, 17] to [8, 10].

Complexity

The work is the number of calls of build, and the nine tiles put a firm limit on it.

  • Time: O(29 ยท k) at most, because each call holds a different increasing group of tiles from 1 to 9, there are 512 such groups, and copying an answer takes k steps. With k = 9 and n = 45, the search makes all 512 calls.
  • Space: O(k) besides the output, because each call adds one tile, so the calls nest at most k + 1 deep, one per tile plus the first call, and combo never holds more than k numbers.

When the numbers come from a given list that may repeat values, instead of the tiles 1 to 9, see Combination Sum II.