Given a list of distinct numbers, candidates, and a number, target, return every combination of candidates that adds up to target. You can use the same number as many times as you like. Two combinations are the same if they use each number the same number of times, so list each one once, in any order.
Examples
Example 1:
Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Example 2:
Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]
Example 3:
Input: candidates = [2], target = 1
Output: []
Example 4:
Input: candidates = [7,3,2], target = 7
Output: [[2,2,3],[7]]
Explanation: the input order does not matter, and neither does the order of the combinations or of the numbers in them.
Backtracking — choose, recurse, undo. The undo is what makes the rest correct. Pruning: cutting a branch the moment it cannot lead anywhere.
How to think about it
1. Use It Again or Step Back Optimal
Intuition
Build a combination one number at a time, keeping its total. After a number goes in, the search goes on from that same number, so it can be used again; it never goes back to an earlier one, so a combination's numbers keep the candidates' order and each combination is found once: [2,4], and never [4,2]. When the total is the target, a copy of the combination is kept, a copy because the one list being built keeps changing; when the total goes over, adding more can only make it bigger, so the search steps back and takes the number out.
Algorithm
1. One combination, shared, and backtrack(start, total) from the first candidate with a total of 0. 2. The total is the target: keep a copy of the combination and return. 3. The total is over the target: return. 4. Otherwise, for each candidate from start on: put it in, call backtrack with the SAME index and the new total, then take it back out.
Time & Space
Time exponential in the target over the smallest candidate: at most about n^(t/m) combinations are tried for n candidates, target t and smallest candidate m, and each copy kept is up to t/m long. Space O(t/m) for the combination and the calls, apart from the answer.
2. DFS That Never Looks Left Optimal
Intuition
Reuse is allowed, so the danger is emitting the same multiset in different orders. Carrying a start index — each level may reuse the current candidate or move right, never left — makes every combination non-descending by construction, which is the dedup. Sorting first also lets the loop stop the moment a candidate exceeds the remainder.
Algorithm
1. Sort the candidates. 2. DFS with a start index and a remaining target. 3. Remaining zero: record the path. 4. Otherwise try each candidate from the start index while it fits, recursing with the SAME index.
Time & Space
Time exponential in the target-to-candidate ratio, which is inherent to enumerating combinations. Space O(target/smallest) for the recursion.