Combination Sum II
List every group of numbers from a list that adds up to a target, using each number at most once and each group once.
Given an array of numbers candidatestargettarget
Example 1
Output: [[1, 1, 6], [1, 2, 5], [1, 7], [2, 6]]
Example 2
Output: [[1, 2, 2], [5]]
The Idea
Picture five coins on a table, worth 2, 5, 2, 1 and 2, and a bill of exactly 5 to pay. You can hand over the 5 coin on its own, or the 1 coin with two of the 2 coins. Those are the two answers of Example 2: [5][1, 2, 2]
But there are three 2 coins, and any two of them go with the 1. That makes three different picks of coins, yet the answer lists [1, 2, 2]
Sorting is a good start: the coins become 1, 2, 2, 2, 5, and equal values sit side by side. Now build a group one number at a time, always taking a number from the positions after the last one taken. Subtract each number from what is still left to pay. When 0 is left, the group is an answer. When the next number is bigger than what is left, every number after it is bigger too, so that path can stop.
Look at the picture below. Each blue box is a group being built, with the amount still left under it, and a teal box is a group that reaches 0, an answer. The lines are the choices, labelled with the number taken.
From the empty group [ ][1, 2][1, 2, 2]
Now look at the box [2, 2][2][1]
The grey boxes are where a path stops: under [1][1, 2, 2]
Solution Approach
Turning that idea into code means settling four things: how to build the groups, how to use each position at most once, how to skip repeated values, and when to stop a path early.
Building the groups one number at a time
How does the code walk through the picture? A method buildcomboremainingstartremainingcombo
Otherwise a loop tries each index istartcandidates[i]combobuildibuild
Using each position once
What stops the same coin from being taken twice? The call for the next number gets i + 1starti
Skipping repeated values
How does the code know a 2 was already tried for this place? Sorting put equal values side by side, so that 2 sits at i - 1i > start && candidates[i] == candidates[i - 1]
The part i > starti == start[2, 2][1, 2, 2]
Why not collect every group and remove the repeats at the end, by putting the groups in a HashSetbuild[1, 2, 2]
Stopping a path early
When can the loop give up? The candidates are sorted, so once candidates[i]remainingbreak
Java Solution
The method combinationSum2
- First, sort the input array with
, so equal values sit next to each other and small values come first.Arrays.sort(candidates) - Create the list
for the answers, and start the search withresult : nothing taken yet, all ofbuild(candidates, target, 0, new ArrayList<>(), result) still needed, and picks starting at index 0.target - In
, ifbuild is 0, add a copy ofremaining tocombo and return. The copy is needed becauseresult itself keeps changing as the search goes on.combo - Otherwise, the index
walks fromi to the last coin. It skips a value equal to the one before it whenstart , and ends withi > start whenbreak is bigger thancandidates[i] .remaining - For any other
, addi tocandidates[i] and callcombo withbuild and startremaining - candidates[i] . Then remove the last number fromi + 1 , so the next coin can take its place.combo - When the first call of
returns,build returnscombinationSum2 .result
The main
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CombinationSumII {
public static List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates); // equal values become neighbours
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 (i > start && candidates[i] == candidates[i - 1]) {
continue; // same value already tried in this position
}
if (candidates[i] > remaining) {
break; // sorted: every later value is too big too
}
combo.add(candidates[i]);
build(candidates, remaining - candidates[i], i + 1, combo, result); // each used once
combo.remove(combo.size() - 1); // take it back, try the next value
}
}
public static void main(String[] args) {
System.out.println(combinationSum2(new int[] {10, 1, 2, 7, 6, 1, 5}, 8));
System.out.println(combinationSum2(new int[] {2, 5, 2, 1, 2}, 5));
System.out.println(combinationSum2(new int[] {1, 1, 1, 1, 1}, 3));
System.out.println(combinationSum2(new int[] {2, 4, 6}, 5));
System.out.println(combinationSum2(new int[] {3, 3}, 6));
}
}
Running it prints:
[[1, 1, 6], [1, 2, 5], [1, 7], [2, 6]]
[[1, 2, 2], [5]]
[[1, 1, 1]]
[]
[[3, 3]]
Look at [[1, 2, 2], [5]][1, 1, 6][1, 2, 5][1, 7]
Five 1s with target 3 print [[1, 1, 1]][][[3, 3]]
That last case is why the skip check says i > starti > 0i > 0[[1, 2, 5], [1, 7], [2, 6]][[5]][1, 1, 6][1, 2, 2][]
Complexity
The work is the number of groups the search builds, plus copying each answer into result
- Time: O(2n ยท n) in the worst case, because each of the n candidates is in a group or not, giving at most 2n calls of
, and copying a found group takes up to n steps. The skip rule and thebuild cut most branches in practice, and the sort, O(n log n), is small next to that.break - Space: O(n) besides the output, because each call of
movesbuild past the number it took, so at most n + 1 calls are open at once andstart holds at most n numbers.combo