Python coding

Reach a target, each item once

Given a list candidates of positive integers, which may contain repeated values, and a positive integer target, return every combination that adds up to target when each entry of candidates is used at most once. Two combinations are the same if they hold the same values the same number of times: with candidates = [1, 1, 2] and target = 3, [1, 2] counts once, whichever 1 it uses. Return each combination once, in any order, with its numbers in any order; if there is none, return an empty list.

1 ≤ len(candidates) ≤ 30, 1 ≤ candidates[i], target ≤ 50. Values may repeat many times, so the answer can be tiny while the number of ways to pick positions is huge.

Besides the tests, one large input (27 candidates, 21 of them 1s) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

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

Backtrack on the remainder over the sorted list: choose an entry, recurse from the next index (i + 1, so nothing is reused), then undo. Stop a loop once a value exceeds the remainder.

Hint 2

Equal values in the same loop start identical subtrees. Skip index i when i > start and it holds the same value as i - 1: each value is tried once per depth, yet can still repeat deeper.

Hint 3

Collecting every combination and removing duplicates with a set gives the right answer, but it still walks every duplicate subtree: twenty 1s with target 10 take over 600,000 paths for one answer.

Solution and why it works
pythonO(2ⁿ · n) in the worst case (all values distinct) · O(n) recursion depth, beyond the output
def sum_combinations_once(candidates: list[int], target: int) -> list[list[int]]:
    nums, res, path = sorted(candidates), [], []

    def bt(start: int, remaining: int) -> None:
        if remaining == 0:
            res.append(path[:])
            return
        for i in range(start, len(nums)):
            if nums[i] > remaining:
                break                              # sorted: every later value is too big too
            if i > start and nums[i] == nums[i - 1]:
                continue                           # same value at the same depth: same subtree
            path.append(nums[i])
            bt(i + 1, remaining - nums[i])         # i + 1: each entry is used at most once
            path.pop()

    bt(0, target)
    return res

Sorting puts equal values side by side. At one depth, choosing the first or the second of two equal values leads to the same subtree, so the loop tries each value once (i > start and equal to its left neighbor: skip), while going deeper from i + 1 still lets a value repeat. Each combination is then built exactly once. The trap is deduplicating at the end with a set: correct, but it walks every duplicate subtree.