Combination Sum III

medium

Find every combination of k distinct numbers, chosen only from the digits 1 through 9, that adds up to exactly n.

Two rules govern which combinations are valid:

  • Only the numbers 1 to 9 may be used.
  • Each number is used at most once within a combination.

Return a list of all valid combinations. The list must not contain the same combination twice, and combinations may be returned in any order. Because each combination is a set of distinct digits, [1,2,4] and [4,2,1] are the same combination — list it once.

Hints

You're choosing a fixed number of distinct digits from a tiny pool — how big is that pool really?
Once you've picked a digit, you never look back at it or any smaller one. What does that suggest about the order you should explore in?
Build the combination one digit at a time and abandon a branch the moment the remaining count or remaining sum can't work — classic backtracking with pruning.

Common doubts

No — each of 19 may be used at most once, so every combination is strictly increasing.
No. Order does not matter; a combination is a set. Always emitting digits in increasing order removes the duplicates for free.
Return an empty list. For example k = 4, n = 1 is impossible because the four smallest distinct digits already sum to 10.

Interview follow-ups

That's Combination Sum — drop the 'move past the current digit' rule and recurse from the same index so a value can repeat.
A dynamic-programming count over (digits used, running sum) avoids materializing every combination.

Fun facts

  • The entire search space is at most 2^9 = 512 subsets — this problem is really a lesson in pruning, not raw scale.
  • The same increasing-order backtracking skeleton powers Combinations, Subsets, and Combination Sum — learn it once, reuse it everywhere.

Asked at

AmazonGoogleMicrosoftAdobe
Frequently Sometimes Occasionally
Example 1
Input: k = 3, n = 7
Output: [[1,2,4]]
1 + 2 + 4 = 7, and there is no other way to pick 3 distinct digits summing to 7.
Example 2
Input: k = 3, n = 9
Output: [[1,2,6],[1,3,5],[2,3,4]]
1 + 2 + 6 = 9, 1 + 3 + 5 = 9, and 2 + 3 + 4 = 9 are the only valid combinations.
Example 3
Input: k = 4, n = 1
Output: []
The smallest sum of 4 distinct digits is 1 + 2 + 3 + 4 = 10 > 1, so no combination exists.
Constraints

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

Solve this problem →