Combination Sum
Problem
Given distinct positive candidates and a target, list every unique combination of candidates that adds up to the target. The same candidate may be used any number of times. Two combinations are the same if they use the same numbers with the same counts.
Examples
Constraints
- • 1 <= candidates.length <= 30
- • 2 <= candidates[i] <= 40, all distinct
- • 1 <= target <= 40
Hints & approach
Hint 1
To avoid listing [2,3] and [3,2] separately, only ever pick candidates at or after the last one you picked.
Hint 2
Because reuse is allowed, recurse with the same start index after choosing a candidate.
Hint 3
Sort first so you can stop the loop once a candidate exceeds the remaining target.
Approachtry the hints first
Backtrack with (start, remaining, path). If remaining is 0, record the path. Otherwise try each candidate from start onward: if it exceeds remaining, stop (candidates are sorted); else push it and recurse with the same index, since it may be reused, and the reduced remaining. Pop after the call returns. Restricting choices to indices >= start makes every combination non-decreasing, which eliminates duplicate orderings for free.
Time O(n^(T/m)), T = target, m = smallest candidate · Space O(T/m) recursion depth