InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Backtracking

Combination Sum III

medium Original ↗ 00:00

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 search space is only the digits 1–9, so there are at most 2^9 = 512 subsets. The problem exists to practice the backtracking template and its pruning arithmetic, not to test performance.

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug