Skip to the workspace
Pebellslearn by building
Backtracking  ›  Lesson

Prune Early: Combinations That Hit a Total

Combination Sum 15 minWhen backtracking toward a target total, sort the values, move forward from a start index so each combination is built once, and cut off a branch as soon as the next value is larger than what remains.

leetcode / Prune Early: Combinations That Hit a Total

Explore each scene at your own pace.

01 · The rule

The rule

Prune Early: Combinations That Hit a Total

A post office sells stamps worth 2, 3 and 5 cents, as many of each as you like. A parcel needs exactly 8 cents of postage. Which stamp combinations work? Listing every possible pile of stamps and then checking the totals would explore a huge tree full of hopeless branches. Good backtracking cuts those branches off the moment they are doomed.

The rule

Stop a branch the moment it can no longer succeed.

Cutting off a doomed branch is called pruning. Here, a branch is doomed as soon as the next stamp is bigger than the postage still needed. Sort the values first, and one such stamp proves every later stamp is too big as well, so the loop can break, not just skip:

def ways_to_total(values, target):
    values = sorted(values)
    result, path = [], []
    def explore(start, remaining):
        if remaining == 0:
            result.append(path[:])
            return
        for i in range(start, len(values)):
            value = values[i]
            if value > remaining:
                break                        # sorted: every later value is bigger too
            path.append(value)
            explore(i, remaining - value)    # i, not i + 1: this stamp may be reused
            path.pop()
    explore(0, target)
    return result

Two other details carry the design:

  • start means each branch only uses stamps at or after the current one. So stamps are always added in sorted order, and [2, 3, 3] can never reappear as [3, 2, 3] or [3, 3, 2].
  • explore(i, ...) lets the same stamp be picked again. Passing i + 1 instead would allow each value at most once.

Pruning never changes which answers are found, only how much of the tree gets visited. For postage of 8 cents the saving is small, but as the target grows, dead branches vastly outnumber live ones, and pruning is what keeps backtracking usable.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.