Recursion and backtracking
Recursion solves a problem through smaller calls to the same function. Backtracking adds a decision, explores the resulting branch, and restores the state before another branch uses it. The restoration is part of correctness, not a memory optimization.
This lesson lists every subset of distinct integer labels. The invented input
is [2, 5, 8]. Each position supplies two decisions, exclude its value or
include it. The result includes the empty subset and preserves input order
within every subset.
Define the recursive state
Section titled “Define the recursive state”The state contains the next index and a mutable path. At index i, path
contains exactly the selected values from positions before i. The remaining
positions are undecided. When i equals the input length, the decisions describe
one complete subset.
The exclude branch leaves path unchanged. The include branch appends the
current value, explores the next index, and then pops that value. After either
branch returns, its caller sees the same path it supplied.
def collect_subsets( values: list[int], index: int, path: list[int], result: list[list[int]], trace: bool = False,) -> None: """Extend a partial subset through include and exclude decisions.
Args: values: Distinct integer labels in input order. index: Next undecided position, between zero and len(values). path: Selected values before index; restored before return. result: Destination for independent copies of completed subsets. trace: Whether to print decisions and restored state. """ if index == len(values): result.append(path.copy()) if trace: print("Save", path) return if trace: print("Exclude", values[index], "path", path) collect_subsets(values, index + 1, path, result, trace) path.append(values[index]) if trace: print("Include", values[index], "path", path) collect_subsets(values, index + 1, path, result, trace) path.pop() if trace: print("Restore after", values[index], "path", path)
def all_subsets(values: list[int], trace: bool = False) -> list[list[int]]: """Return all subsets of distinct integer labels.
Args: values: Distinct integer labels; the input remains unchanged. trace: Whether to print decisions and restored state.
Returns: Independent subset lists in exclude-before-include order. """ result: list[list[int]] = [] collect_subsets(values, 0, [], result, trace) return result
values = [2, 5, 8]subsets = all_subsets(values, trace=True)print("All subsets:", subsets)print("Subset count:", len(subsets))print("Input after the search:", values)Exclude 2 path []Exclude 5 path []Exclude 8 path []Save []Include 8 path [8]Save [8]Restore after 8 path []Include 5 path [5]Exclude 8 path [5]Save [5]Include 8 path [5, 8]Save [5, 8]Restore after 8 path [5]Restore after 5 path []Include 2 path [2]Exclude 5 path [2]Exclude 8 path [2]Save [2]Include 8 path [2, 8]Save [2, 8]Restore after 8 path [2]Include 5 path [2, 5]Exclude 8 path [2, 5]Save [2, 5]Include 8 path [2, 5, 8]Save [2, 5, 8]Restore after 8 path [2, 5]Restore after 5 path [2]Restore after 2 path []All subsets: [[], [8], [5], [5, 8], [2], [2, 8], [2, 5], [2, 5, 8]]Subset count: 8Input after the search: [2, 5, 8]The two branches partition every valid subset according to whether it contains the current position. They cannot produce the same positional choice. Repeating that partition until no position remains proves that the algorithm produces every choice once.
The helper is a module-level function. Passing state explicitly makes the
mutation and restoration visible. There is no shared global path and no state
left over from an earlier call.
Copy at the leaf
Section titled “Copy at the leaf”result.append(path) would store another reference to the same mutable list.
Later pops would change every stored reference. path.copy() creates a
separate list of selected references at each leaf. Because these values are
integers, no deeper copy is needed.
assert all_subsets([]) == [[]]assert all_subsets([4]) == [[], [4]]result = all_subsets([2, 5])assert len({id(subset) for subset in result}) == len(result)result[0].append(99)assert result[1:] == [[5], [2], [2, 5]]assert all_subsets([2, 5]) == [[], [5], [2], [2, 5]]print("The empty input and independent-output checks pass.")The empty input and independent-output checks pass.The distinct-input contract matters. If the input contains equal values at different positions, this algorithm still explores distinct position choices, but its value lists can repeat. A problem that requests unique value subsets needs an additional duplicate policy.
Count the search and its output
Section titled “Count the search and its output”For n values, the binary decision tree has 2ⁿ leaves and 2ⁿ⁺¹ - 1 calls.
For n >= 1, exactly half of all subsets contain each value. The returned lists
therefore contain n * 2ⁿ⁻¹ selected references in total.
The function costs Theta(n * 2ⁿ) time because it copies each completed subset.
Its path and recursive calls use O(n) auxiliary space. The returned lists use
Theta(n * 2ⁿ) output space. The empty input still needs one empty output list.
Trace mode also prints each decision and path; it is a diagnostic option.
Large n fails through output growth long before this becomes a useful method
for arbitrary-size inputs. A recursion limit is a separate constraint. A
generator can avoid retaining every subset, but it cannot avoid the work of
producing every requested subset.
Transfer the pattern
Section titled “Transfer the pattern”For permutations, the state records which positions remain available. For a constraint problem, reject a partial choice as soon as it violates a necessary condition. Such pruning is valid only when no future choice can repair that violation. State that argument before skipping a branch.
An include or exclude search suits subsets. It does not automatically give the right state for every recursive problem. Tree traversal, for example, visits existing nodes instead of creating alternative choices.
Prune a branch that cannot reach its target
Section titled “Prune a branch that cannot reach its target”Now select distinct positive values whose sum equals a target. Each input value can appear at most once in a selection. Sort a copy of the input, then track the remaining amount and the first position still available.
When a candidate exceeds the remaining amount, every later candidate also exceeds it. No positive value can repair that excess, so the search can stop this loop. Negative values would invalidate the argument and are rejected.
def collect_target_groups( values: list[int], start: int, remaining: int, path: list[int], result: list[list[int]],) -> None: """Collect target-sum groups from a sorted positive suffix.
Args: values: Sorted distinct positive integers. start: First index still available for selection. remaining: Nonnegative amount still required. path: Current choices, restored before the function returns. result: Destination for independent completed choices. """ if remaining == 0: result.append(path.copy()) return for index in range(start, len(values)): value = values[index] if value > remaining: break path.append(value) collect_target_groups( values, index + 1, remaining - value, path, result ) path.pop()
def target_groups(values: list[int], target: int) -> list[list[int]]: """Return distinct positive-value subsets that sum to a target.
Args: values: Distinct positive integers. The input remains unchanged. target: Nonnegative required sum.
Returns: Increasing-value subsets in traversal order. A zero target returns one empty subset, including when the input is empty.
Raises: ValueError: If target is negative or values repeat or are nonpositive. """ if target < 0 or any(value <= 0 for value in values): raise ValueError("values must be positive and target nonnegative") if len(set(values)) != len(values): raise ValueError("values must be distinct") ordered = sorted(values) result = [] collect_target_groups(ordered, 0, target, [], result) return result
candidates = [8, 2, 6, 3]print("Target groups:", target_groups(candidates, 8))print("Original input:", candidates)print("Zero target:", target_groups(candidates, 0))print("Unreachable target:", target_groups([4, 6], 5))Target groups: [[2, 6], [8]]Original input: [8, 2, 6, 3]Zero target: [[]]Unreachable target: []Advancing to index + 1 prevents reuse of a selected value. Increasing indices
also prevent another traversal from generating the same subset in a different
order. Each recursive call removes its selected value before the next branch
starts, preserving the caller’s path.
Pruning reduces work for some inputs but does not establish a polynomial
bound. A safe upper bound is O(n log n + n 2^n) time, including sorting,
search, and copies of completed choices. Auxiliary storage is O(n) for the
sorted copy, path, validation set, and recursive stack. Returned choices occupy
additional output space.
assert target_groups([], 0) == [[]]assert target_groups([], 4) == []assert target_groups([2, 3], 4) == []assert target_groups([8, 2, 6, 3], 8) == [[2, 6], [8]]practice_groups = target_groups([1, 2, 3], 3)practice_groups[0].append(99)assert practice_groups[1] == [3]print("Empty, zero-target, single-use, and independent-result checks pass.")Empty, zero-target, single-use, and independent-result checks pass.Practice
Section titled “Practice”Subsets tests the decision tree and the independence of returned lists. Count the expected number of outputs before you inspect their order.
Permutations changes the decision from include or exclude to which unused value comes next. Explain what you must restore after a recursive call.
Download the Python source to run the complete example locally.
Further reading
Section titled “Further reading”Python’s list operations describe append, pop, and shallow copy. These operations create and restore the path while preserving completed outputs.
Python’s itertools combinations provide a library alternative for subsets of a fixed size. Compare its position-based treatment of inputs with the distinct-label contract here.