Combination Sum III

Pattern: Combination sum

medium

Choose k different digits from 1 to 9, in increasing order, that add up to n. Each call picks the next digit above the last one; a branch ends when it has k digits.

The problem

Find every combination of k different digits from 1 to 9 that adds up to n. Each digit is used at most once. For example, k = 3, n = 7 gives [1, 2, 4], and k = 3, n = 9 gives [1, 2, 6], [1, 3, 5] and [2, 3, 4].

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

Think first

  • How do you keep digits different and avoid listing [2, 1, 4] as well as [1, 2, 4]?
  • When is a branch complete?
  • When can a branch stop early?

Hints

    Brute force, and why it fails

    Check all 2⁹ = 512 subsets of the digits. That is already fast. The increasing-order search does the same job with early stops.

    The key insight

    With a fixed set of 9 candidates and no repeats, increasing order is the simplest way to make every combination appear once.

    Dry run

    cur[]
    left9

    k = 3 and n = 9. Start with no digits and 9 left.

    Step 1 of 4

    The plan

    function build(next, left, cur):
        if len(cur) == k:
            if left == 0: record a copy of cur
            return
        for d from next to min(9, left):
            add d; build(d + 1, left - d, cur); remove it
    build(1, n, [])
    

    Complexity

    Time
    O(C(9, k) × k)
    Space
    O(k)

    At most C(9, k) combinations, each k digits long. The recursion is k deep.

    Edge cases

    • k = 9, n = 45: all nine digits.
    • Impossible, as in k = 4, n = 1: empty.
    • k = 2, n = 18: empty, since 9 cannot be used twice.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<List<Integer>> combinationSum3(int k, int n) {
            List<List<Integer>> out = new ArrayList<>();
            build(1, k, n, new ArrayList<>(), out);
            return out;
        }
    
        private void build(int next, int k, int left, List<Integer> cur, List<List<Integer>> out) {
            if (cur.size() == k) { if (left == 0) out.add(new ArrayList<>(cur)); return; }
            for (int d = next; d <= 9 && d <= left; d++) {   // digits in increasing order, each at most once
                cur.add(d);
                build(d + 1, k, left - d, cur, out);
                cur.remove(cur.size() - 1);
            }
        }
    }

    C++

    class Solution {
    public:
        vector<vector<int>> combinationSum3(int k, int n) {
            vector<vector<int>> out;
            vector<int> cur;
            build(1, k, n, cur, out);
            return out;
        }
    
        void build(int next, int k, int left, vector<int>& cur, vector<vector<int>>& out) {
            if (static_cast<int>(cur.size()) == k) { if (left == 0) out.push_back(cur); return; }
            for (int d = next; d <= 9 && d <= left; d++) {   // digits in increasing order, each at most once
                cur.push_back(d);
                build(d + 1, k, left - d, cur, out);
                cur.pop_back();
            }
        }
    };

    Python

    class Solution:
        def combinationSum3(self, k: int, n: int) -> list[list[int]]:
            out = []
    
            def build(nxt: int, left: int, cur: list) -> None:
                if len(cur) == k:
                    if left == 0:
                        out.append(cur[:])
                    return
                for d in range(nxt, min(9, left) + 1):   # digits in increasing order, each at most once
                    cur.append(d)
                    build(d + 1, left - d, cur)
                    cur.pop()
    
            build(1, n, [])
            return out

    Common mistakes

    • Starting each level at 1, which repeats digits and orders.
    • Forgetting to check the count k as well as the sum.
    • Allowing digits above 9.

    Similar problems