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 candidates, which may contain repeated values, and a number target, return every combination of candidates whose sum is target. A combination is a group of numbers picked from the array, in any order. Each position of the array may be used at most once in a combination, and two combinations with the same values count as one, so each must appear only once.

Example 1
Input: candidates = [10, 1, 2, 7, 6, 1, 5], target = 8
Output: [[1, 1, 6], [1, 2, 5], [1, 7], [2, 6]]
Example 2
Input: candidates = [2, 5, 2, 1, 2], target = 5
Output: [[1, 2, 2], [5]]
Solution

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] and [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] once. So how do we search through the picks without building the same group of values twice?

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.

Choice tree for the sorted candidates 1, 2, 2, 2, 5 and target 5. From the empty group the search takes 1, 2 or 5, and skips the second and third 2. Taking 1, then 2, then 2 finds [1, 2, 2], and taking 5 finds [5]. Grey boxes mark a number too big for what is left.

From the empty group [ ] with 5 left, the search takes 1, the first 2, or 5. Taking the second or the third 2 instead would start exactly the same groups as the first 2, so the orange box at the top skips them. The same happens lower down: [1, 2] takes one more 2 and finds [1, 2, 2], and the orange box next to it skips the third 2.

Now look at the box [2, 2]. A second 2 comes right after the first one, and that is allowed. The rule is not "never use a value twice". It is "for one place in the group, try each value once". Under [2], the next 2 is the first number tried for the second place, so it is taken. To keep the picture small, it leaves out a few more skipped 2s, such as those under [1].

The grey boxes are where a path stops: under [1], 5 is too big for the 4 left. When a path ends, the search takes back the last number and tries the next one. After finding [1, 2, 2], it takes back both 2s and the 1, and tries 2 as the first number. Adding coins to a group one at a time, and taking the last coin back to try a different one, is called backtracking.

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 build gets the numbers taken so far in a list combo and the amount still needed in remaining. It also gets start, the first index (position in the sorted array) it may pick from. If remaining is 0, combo is an answer.

Otherwise a loop tries each index i from start on. It adds candidates[i] to combo, calls build again to fill in the rest, and then removes that number, so the next i starts from the same group. Each call of build is one blue or teal box in the picture, and the calls it makes are the boxes under it.

Using each position once

What stops the same coin from being taken twice? The call for the next number gets i + 1 as its start, so it only looks at positions after the one just taken. In Combination Sum, where a number may be used again and again, the next call starts at i instead.

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 - 1. The check is i > start && candidates[i] == candidates[i - 1], and a number that passes it is skipped.

The part i > start matters. At i == start, the number is the first one tried for this place, so it is taken even when it equals the number before it. The number before it was taken for the previous place, which is how [2, 2] and [1, 2, 2] come about.

Why not collect every group and remove the repeats at the end, by putting the groups in a HashSet, which keeps each group once? That gives the right answer, but the search still walks every repeated branch. For Example 2, build is called 7 times with the skip rule, one call per blue or teal box. Without it, it is called 15 times and finds [1, 2, 2] three times.

Stopping a path early

When can the loop give up? The candidates are sorted, so once candidates[i] is bigger than remaining, every later number is too. So the loop stops with break rather than testing those bigger coins. Each grey box in the picture is such a stop.

Java Solution

The method combinationSum2 works in these steps:

  1. First, sort the input array with Arrays.sort(candidates), so equal values sit next to each other and small values come first.
  2. Create the list result for the answers, and start the search with build(candidates, target, 0, new ArrayList<>(), result): nothing taken yet, all of target still needed, and picks starting at index 0.
  3. In build, if remaining is 0, add a copy of combo to result and return. The copy is needed because combo itself keeps changing as the search goes on.
  4. Otherwise, the index i walks from start to the last coin. It skips a value equal to the one before it when i > start, and ends with break when candidates[i] is bigger than remaining.
  5. For any other i, add candidates[i] to combo and call build with remaining - candidates[i] and start i + 1. Then remove the last number from combo, so the next coin can take its place.
  6. When the first call of build returns, combinationSum2 returns result.

The main method runs both examples, five 1s with target 3, three even numbers with an odd target, and two 3s that only reach the target together.

Java
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:

Output
[[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]], the two groups found in the picture. In the line above it, from Example 1, [1, 1, 6] uses both 1s, while [1, 2, 5] and [1, 7] appear once each, even though either 1 could start them.

Five 1s with target 3 print [[1, 1, 1]]: there are ten ways to pick three of the five positions, and the group is listed once. The empty [] comes from 2, 4 and 6 with target 5, since even numbers never add up to an odd sum. The last line, [[3, 3]], takes the second 3 because it is the first number tried for the second place.

That last case is why the skip check says i > start and not i > 0. With i > 0, a value equal to its left neighbour is skipped everywhere. Running that version prints [[1, 2, 5], [1, 7], [2, 6]] for Example 1 and [[5]] for Example 2, losing [1, 1, 6] and [1, 2, 2]. For the two 3s it prints [].

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 build, and copying a found group takes up to n steps. The skip rule and the break cut most branches in practice, and the sort, O(n log n), is small next to that.
  • Space: O(n) besides the output, because each call of build moves start past the number it took, so at most n + 1 calls are open at once and combo holds at most n numbers.