sagelearnai

Combination Sum III

Difficulty: Medium · Pattern: Backtracking · LeetCode #216

Find all combinations of k distinct numbers from 1–9 that add up to n. Return them in lexicographic order.

Examples

text
k = 3, n = 7  →  [[1,2,4]]
k = 3, n = 9  →  [[1,2,6],[1,3,5],[2,3,4]]
k = 4, n = 1  →  []

Hints

  1. Pick the digits in increasing order. Stop when the path has k numbers.
  2. Prune as soon as the next digit is larger than the remaining sum.

Approach

bt(start, rem): if len(path) == k, record the path when rem == 0. Otherwise try d from start to 9, breaking when d > rem. The search space is at most C(9, k) ≤ 126, so this is effectively constant time.

Complexity

Time: O(C(9,k) · k). Space: O(k).

Python solution
def combinationSum3(k, n):
    res, path = [], []
    def bt(start, rem):
        if len(path) == k:
            if rem == 0:
                res.append(path[:])
            return
        for d in range(start, 10):
            if d > rem:
                break
            path.append(d)
            bt(d + 1, rem - d)
            path.pop()
    bt(1, n)
    return res
JavaScript solution
function combinationSum3(k, n) {
  const res = [], path = [];
  const bt = (start, rem) => {
    if (path.length === k) { if (rem === 0) res.push([...path]); return; }
    for (let d = start; d <= 9 && d <= rem; d++) { path.push(d); bt(d + 1, rem - d); path.pop(); }
  };
  bt(1, n);
  return res;
}