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 candidatestargettarget
Example 1
Output: [[2, 2, 3], [7]]
Example 2
Output: [[2, 2, 2, 2], [2, 3, 3], [3, 5]]
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][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]
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.
From the empty group [ ][2][3][3, 2][2, 3][7][2, 2, 3]
The grey boxes are dead ends. In [2, 2, 2][2, 2]
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 buildcomboremainingstartremainingcombo
Otherwise a loop moves an index istarticandidates[i]combobuildi
Letting a number repeat
How can [2, 2, 3]candidates[i]istarti + 1i + 1[[7]][[3, 5]]
Keeping each group in sorted order
Why pass start[2, 2, 3][2, 3, 2][3, 2, 2]start
The version without startbuild
Stopping a path early
When can a loop give up? If the candidates are sorted first, then once candidates[i]remainingbreak
Java Solution
The method combinationSum
- First, sort the input array with
, so small values come first.Arrays.sort(candidates) - Create the list
for the answers, and start the search withresult : an empty group, all ofbuild(candidates, target, 0, new ArrayList<>(), result) still needed, and choices starting at index 0.target - In
, whenbuild is 0, add a copy ofremaining tocombo and return. It must be a copy, since numbers keep being added to and removed fromresult after this point.combo - Otherwise, a loop moves
fromi to the end of the array. It ends withstart as soon asbreak is more thancandidates[i] .remaining - For any other
, addi tocandidates[i] and callcombo withbuild andremaining - candidates[i] as itsi . Then remove the last number fromstart , so the loop can try the next value.combo - When the first call of
returns,build returnscombinationSum .result
The main
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:
[[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]][[2, 2, 3], [7]]
The line [[1, 1, 1]]ibuildbreak
Complexity
The work is one call of build
- 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
and the chain of unfinished calls never hold more than T/m numbers.combo
When each number may be used only once and the input can repeat values, see