Because each number can be reused, this is not a simple “include or exclude” subset problem — at every step we choose how many more times to use the current candidate (including zero) before moving on to the next one.
Brute Force: Generate-and-Filter
Time exponentialSpace exponentialRecurse over “use candidate i, or don’t” like Subsets, but allow re-using an index unboundedly, and only check the sum against target once a full combination is built. Without pruning on the running sum, this explores far more branches than necessary — for example it keeps recursing even after the partial sum has already exceeded target.
class Solution: def combinationSum(self, candidates: list[int], target: int) -> list[list[int]]: result = [] path = []
def backtrack(start, path_sum): if path_sum == target: result.append(path[:]) return if start == len(candidates): return # option 1: use candidates[start] again if path_sum + candidates[start] <= target: path.append(candidates[start]) backtrack(start, path_sum + candidates[start]) path.pop() # option 2: move on to the next candidate backtrack(start + 1, path_sum)
backtrack(0, 0) return resultThis already has the path_sum <= target check, otherwise it degenerates into infinite recursion (reusing a positive number forever). Even with it, branching into “use again” and “skip” at every node explores overlapping work that the loop-based version below avoids.
Backtracking with a For-Loop and Pruning
OptimalTime O(n^(t/m + 1))Space O(t/m)Sort the candidates first. At each recursive call, loop over candidates starting from the current index (allowing the same index to be reused on the next call), and stop the loop as soon as a candidate exceeds the remaining budget — since the array is sorted, everything after it is too large as well.
class Solution: def combinationSum(self, candidates: list[int], target: int) -> list[list[int]]: candidates.sort() result = [] path = []
def backtrack(start, remaining): if remaining == 0: result.append(path[:]) return for i in range(start, len(candidates)): if candidates[i] > remaining: break # sorted, so nothing further can fit either path.append(candidates[i]) backtrack(i, remaining - candidates[i]) # i, not i+1: reuse allowed path.pop()
backtrack(0, target) return resultTracing candidates = [2,3,6,7], target = 7 (sorted already) as a decision tree, where each node is a partial sum and a branch is discarded once it would overshoot:
Start at sum 0, remaining target 7. Try candidates from index 0 onward.
Complexity: in the worst case (candidates like [1] with a large target) the recursion depth is t/m where m is the smallest candidate, and each level branches over n candidates, giving O(n^(t/m + 1)) time; the recursion stack and path are bounded by that same depth → O(t/m) space. Sorting first lets the break prune entire subtrees early rather than visiting every combination that overshoots.