Python coding

Reach a target, reuse allowed

Given a list candidates of distinct positive integers and a positive integer target, return every combination of candidates that adds up to target. Any candidate may be used as many times as you like. Two combinations are the same if they use the same numbers the same number of times, so return each one once; the order of combinations and of numbers inside them does not matter.

1 ≤ len(candidates) ≤ 10, 1 ≤ candidates[i], target ≤ 40.

  • sum_combinations([2,3,6,7], 7) → [[2,2,3],[7]]
  • sum_combinations([2,3,5], 8) → [[2,2,2,2],[2,3,3],[3,5]]
  • sum_combinations([2], 1) → []
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Backtrack on the remainder: choose a candidate, subtract it, recurse, undo. Record path when the remainder reaches 0; give up when it would go negative.

Hint 2

Recurse with the same index i, not i + 1, so a number can repeat, and never revisit earlier indexes. Sort first so you can break once a candidate exceeds the remainder.

Solution and why it works
pythonO(n^(t/m)), t = target, m = smallest candidate · O(t/m) recursion depth, beyond the output
def sum_combinations(candidates: list[int], target: int) -> list[list[int]]:
    nums = sorted(candidates)
    res, path = [], []

    def bt(start: int, remain: int) -> None:
        if remain == 0:
            res.append(path[:])
            return
        for i in range(start, len(nums)):
            if nums[i] > remain:
                break
            path.append(nums[i])
            bt(i, remain - nums[i])
            path.pop()

    bt(0, target)
    return res

Recursing with i lets the same number be chosen again, while starting each loop at start keeps every combination in non-decreasing order, so [2, 2, 3] is built once and its reorderings never are. Sorting first turns pruning into a break: once a candidate exceeds the remainder, every later one does too. The trap is looping from index 0 at every level, which returns each combination once per ordering.