InterviewPrepKit

Home / Coding / Backtracking

Combination Sum III

medium Original β†—
Solving tips
  • Backtrack over digits 1-9 with a start digit and recurse with d+1 so each digit is used at most once and combinations stay in increasing order.
  • A leaf counts only when BOTH len(path) == k AND remaining == 0; checking only the sum accepts wrong-length sets.
  • Break the loop early when d > remaining (digits ascend), and optionally add a slot-capacity window prune: with s slots left, feasible sums lie in [s*start + s(s-1)/2, 9s - s(s-1)/2].
  • The whole universe is 2^9 = 512 subsets, so complexity is O(C(9,k)*k); pruning is about habit, not survival.

Problem

Find all combinations of exactly k distinct numbers that sum to n, where every number must come from 1 through 9 and each number may appear at most once per combination. Return the list of all such combinations; no combination may appear twice (as a set of numbers), and any output order is acceptable.

Examples

  • k = 3, n = 7 β†’ [[1,2,4]] β€” the only trio of distinct digits summing to 7.
  • k = 3, n = 9 β†’ [[1,2,6],[1,3,5],[2,3,4]] β€” three valid trios.
  • k = 4, n = 1 β†’ [] β€” the smallest 4 distinct digits already sum to 1+2+3+4 = 10 > 1.

Constraints

  • 2 <= k <= 9
  • 1 <= n <= 60

The universe is only the digits 1–9, so the whole search space is 2^9 = 512 subsets β€” tiny. The problem is a clean sandbox for the backtracking template and its pruning arithmetic rather than a performance fight.

Think about it first

Hint 1 Only digits 1..9, each used at most once. How many subsets of {1,...,9} exist in total? Could you afford to look at every one of them?
Hint 2 Build combinations in increasing order with a start digit, tracking how many numbers you've placed and what remains of n. What two conditions must hold at a leaf for the path to count?
Hint 3 Prune with arithmetic: if the remaining sum is smaller than the next candidate digit, or larger than the sum of the biggest digits you could still take (9 + 8 + ... for the remaining slots), the branch is dead. Stop the loop early since digits ascend.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.