Combination Sum II

Pattern: Combination sum

medium

Sort the candidates. Pick the next number from a start index, each at most once, and skip a value equal to the previous one at the same depth so equal numbers never start the same combinations twice. Stop the loop once a number is bigger than what is left.

The problem

Given candidates (which may repeat) and a target, return every distinct combination that adds up to the target, using each candidate at most once. For example, [10, 1, 2, 7, 6, 1, 5] with target 8 gives [1, 1, 6], [1, 2, 5], [1, 7] and [2, 6].

The function name combinationSum2 matches LeetCode. Use the link above for the exact statement and limits. The tests sort before comparing.

Think first

  • How is this different from Combination Sum?
  • With two 1s, why could [1, 7] appear twice?
  • Why does sorting let the loop stop early?

Hints

    Brute force, and why it fails

    Try every subset, keep those with the right sum, and remove duplicates with a set: O(2ⁿ × n). The skip rule and the early break avoid both the duplicates and most of the subsets.

    The key insight

    This combines two earlier ideas: "each used once" from Subsets, and "skip equal values at the same depth" from Subsets II.

    Dry run

    10 
    11 
    22 
    53 
    64 
    75 
    106 

    candidates = [10, 1, 2, 7, 6, 1, 5] and target = 8. Sorted, they are 1 1 2 5 6 7 10.

    Step 1 of 4

    The plan

    sort c
    function build(start, left, cur):
        if left == 0: record a copy of cur; return
        for i from start while i < n and c[i] <= left:
            if i > start and c[i] == c[i - 1]: continue
            add c[i]; build(i + 1, left - c[i], cur); remove it
    build(0, target, [])
    

    Complexity

    Time
    O(2ⁿ × n)
    Space
    O(n)

    At most every subset is explored, each copied in O(n) when recorded. The recursion is n deep.

    Edge cases

    • All candidates equal, as in [1, 1, 1, 1] with target 2: [1, 1] once.
    • Nothing works: empty.
    • One candidate equal to the target: a combination of one.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<List<Integer>> combinationSum2(int[] candidates, int target) {
            int[] c = candidates.clone();
            Arrays.sort(c);
            List<List<Integer>> out = new ArrayList<>();
            build(c, 0, target, new ArrayList<>(), out);
            return out;
        }
    
        private void build(int[] c, int start, int left, List<Integer> cur, List<List<Integer>> out) {
            if (left == 0) { out.add(new ArrayList<>(cur)); return; }
            for (int i = start; i < c.length && c[i] <= left; i++) {   // sorted: bigger values only overshoot more
                if (i > start && c[i] == c[i - 1]) continue;           // same value at the same depth: a repeat
                cur.add(c[i]);
                build(c, i + 1, left - c[i], cur, out);                // each candidate used at most once
                cur.remove(cur.size() - 1);
            }
        }
    }

    C++

    class Solution {
    public:
        vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
            vector<int> c = candidates;
            sort(c.begin(), c.end());
            vector<vector<int>> out;
            vector<int> cur;
            build(c, 0, target, cur, out);
            return out;
        }
    
        void build(vector<int>& c, size_t start, int left, vector<int>& cur, vector<vector<int>>& out) {
            if (left == 0) { out.push_back(cur); return; }
            for (size_t i = start; i < c.size() && c[i] <= left; i++) {   // sorted: bigger values only overshoot more
                if (i > start && c[i] == c[i - 1]) continue;              // same value at the same depth: a repeat
                cur.push_back(c[i]);
                build(c, i + 1, left - c[i], cur, out);                   // each candidate used at most once
                cur.pop_back();
            }
        }
    };

    Python

    class Solution:
        def combinationSum2(self, candidates: list[int], target: int) -> list[list[int]]:
            c = sorted(candidates)
            out = []
    
            def build(start: int, left: int, cur: list) -> None:
                if left == 0:
                    out.append(cur[:])
                    return
                for i in range(start, len(c)):
                    if c[i] > left:
                        break                       # sorted: bigger values only overshoot more
                    if i > start and c[i] == c[i - 1]:
                        continue                    # same value at the same depth: a repeat
                    cur.append(c[i])
                    build(i + 1, left - c[i], cur)  # each candidate used at most once
                    cur.pop()
    
            build(0, target, [])
            return out

    Common mistakes

    • Recursing on i instead of i + 1, which reuses a candidate.
    • Skipping with i > 0, which loses combinations like [1, 1, 6].
    • Forgetting to sort.

    Similar problems