Coding Interview PatternsCombination Sum III
MediumSubsets
Combination Sum III
Explanation & Solution
Description
Find all valid combinations of k numbers that sum up to n such that the following conditions are true:
- Only numbers
1through9are used - Each number is used at most once
Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order.
Input: k = 3, n = 7
Output: [[1,2,4]]
Explanation: 1 + 2 + 4 = 7. There are no other valid combinations.
Constraints
2 <= k <= 91 <= n <= 60
Approach
Subsets pattern
1. Set Up Backtracking
- Create an empty
resultarray to collect valid combinations - Begin recursion from
start = 1with an emptycurrentarray andremaining = n
2. Base Case — Correct Length Reached
- When
current.length === k, check ifremaining === 0 - If so, the current combination uses exactly
knumbers that sum ton— add it toresult - Return regardless, since we cannot add more numbers
3. Iterate Through Digits 1-9
- Loop from
startto9to ensure each number is used at most once and combinations are generated in increasing order - If the current number
iexceedsremaining, break early — all subsequent numbers are even larger
4. Choose and Explore
- Push
iontocurrentand recurse withstart = i + 1andremaining - i - After recursion, pop
ifromcurrent(backtrack) to try the next candidate
5. Return All Valid Combinations
- After all paths are explored,
resultcontains every unique combination ofknumbers from 1-9 that sum ton
Key Insight
- The search space is small (only digits 1-9), so the algorithm is very efficient despite being exponential in theory
- By iterating from
startonward, each combination is generated in strictly increasing order, which naturally avoids duplicates
Time
**O(C(9, k))** — at most choosing k elements from 9Space
O(k) for the recursion stack depth