Combination Sum III
List every group of k different numbers from 1 to 9 whose sum is n, each group once.
Given two numbers knkn[4, 1, 2][1, 2, 4]
Example 1
Output: [[1, 2, 4]]
Example 2
Output: [[1, 2, 6], [1, 3, 5], [2, 3, 4]]
Example 3
Output: []
Explanation: the smallest sum of four different numbers is 1 + 2 + 3 + 4 = 10.
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.
The search starts at the empty group [ ][1, 2][1, 2, 3][1, 2, 4]
Then the search puts the 2 back and tries 3 as the second tile. The box [1, 3]
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 buildcomboremainingstartnumstartnumcombobuildnum
Each call of buildnum
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][2, 1, 4]num + 1startcombo
When a path stops
When can a call give up? At the top of buildcombokcomboremainingk
The loop itself runs while num <= 9 && num <= remainingnum
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
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
- First, create the list
for the answers and start the search withresult : no tiles taken yet, all ofbuild(k, n, 1, new ArrayList<>(), result) still left, and 1 as the smallest tile allowed.n - In
, ifbuild already holdscombo tiles, add a copy of it tok whenresult is 0, and return either way. The copy is needed becauseremaining keeps changing as the search goes on.combo - Otherwise, a loop moves
up fromnum , as long asstart is at most 9 and at mostnum .remaining - For each
, add it tonum and callcombo withbuild left andremaining - num as the newnum + 1 . Then remove the last number fromstart , so the loop can try the next tile.combo - When the first call of
returns,build returnscombinationSum3 .result
The main
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:
[[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, []build
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]]
That empty line depends on the num <= 9num <= remaining[1, 17][8, 10]
Complexity
The work is the number of calls of build
- 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
steps. Withk andk = 9 , the search makes all 512 calls.n = 45 - Space: O(k) besides the output, because each call adds one tile, so the calls nest at most
deep, one per tile plus the first call, andk + 1 never holds more thancombo numbers.k
When the numbers come from a given list that may repeat values, instead of the tiles 1 to 9, see