Combination Sum III – Solution & Complexity
Solution Walkthrough
Step 1: Recognize the search space
- You are choosing exactly
kdistinct digits from the fixed set1..9, so this is a small combinatorial backtracking problem. - Distinctness and increasing order come naturally if each recursive call only considers later digits than the one just chosen.
- Because each level tries digits in ascending order, the DFS itself produces the required canonical output order without any post-sorting.
- You are choosing exactly
Step 2: Plain backtracking with increasing digits
- Keep a
pathfor the current combination, astartdigit for the next choice, and the running sum so far. - If the path already has
kdigits, record it only when the sum is exactlyn. - Otherwise, try every next digit from
startthrough9, recurse withdigit + 1, then undo the choice. - This baseline already guarantees no repeated digits, increasing order inside each combination, and canonical DFS order across the answer list.
- Keep a
Step 3: Prune impossible branches earlier
- The baseline works because the search space is tiny, but you can cut many branches before recursing.
- If you still need
remaining_countdigits, the smallest possible extra sum comes from taking the nextremaining_countconsecutive digits starting atstart. - The largest possible extra sum comes from taking the biggest
remaining_countdigits ending at9. - If
remaining_sumfalls outside that[min_possible, max_possible]range, this branch can never succeed and should stop immediately.
Step 4: Final optimized solution and complexity
Backtracking still explores combinations in the exact same canonical order, but arithmetic bounds prune branches whose remaining slots cannot possibly add up to the target. The search uses
O(k)extra recursion/path space, and the total work isO(C(9, k) * k)in the worst case because every valid or explored combination prefix has length at mostk.