Combination Sum II – Solution & Complexity
Solution Walkthrough
Step 1: Recognize the once-only search space
- This is backtracking over indices, not over unlimited value reuse: once you take
candidates[i], the next recursive call must continue fromi + 1. - Duplicate values in the input are the real twist. If two equal numbers sit next to each other in the sorted array, starting a branch from both of them at the same recursion depth would create duplicate combinations.
- Sorting first gives you both pieces you need: deterministic canonical order and an easy adjacent-value check for duplicate skipping.
- This is backtracking over indices, not over unlimited value reuse: once you take
Step 2: Baseline backtracking with same-level duplicate skipping
- Sort the array, keep a
path, and let each call choose the next index fromstartonward. - When
remaining == 0, record the current path immediately; that DFS discovery order is the required outer-list order. - At a given recursion depth, skip
candidates[i]wheni > startand it matchescandidates[i - 1]. That preserves one representative branch per equal-value run at that level. - This baseline is fully correct, but it may still recurse into branches that already overshoot the target.
- Sort the array, keep a
Step 3: Add sorted-array pruning
- After sorting, once
candidates[i]is already larger than the remaining target, every later value is also too large. - That means the current loop can
breakimmediately instead of recursing into guaranteed failures. - This optimization preserves the exact same canonical output order because it only removes branches that could never produce a valid combination.
- After sorting, once
Step 4: Final optimized solution and complexity
The algorithm sorts once, then backtracks left-to-right while skipping equal values at the same depth and breaking when the next candidate is too large. In the worst case it explores subset-style branches, so the time complexity is
O(n * 2^n)and the extra recursion/path space isO(n)(excluding the returned output).Step 5: Common mistakes to watch for
- Reusing the same index by recursing with
iinstead ofi + 1, which accidentally turns the problem back into Combination Sum I. - Skipping every duplicate globally instead of only duplicates at the same recursion depth. You still need to allow
[1,1,6]when two separate1entries exist. - Sorting after backtracking or post-sorting the output, which can hide ordering bugs instead of producing the required canonical DFS order directly.
- Reusing the same index by recursing with