M31 · Backtracking

Backtracking: Subsets and Permutations on a Decision Tree

Backtracking builds an answer one decision at a time. At each step it makes a choice, explores everything that follows from it, then undoes the choice and tries the next one. Drawn as a tree, every path from the root to a leaf is one complete answer, and the algorithm is a depth-first walk of that tree.

~40 minIntermediateC# · Python · Java · C++
Curriculum: M31 Backtracking · 1 of 1 lessons available

You will be able to

  • Describe a backtracking search as a depth-first walk of a decision tree, and say what a node, an edge and a leaf mean.
  • Write the choose, explore, unchoose pattern for subsets and for permutations, keeping one shared partial answer.
  • Count the calls and answers: 2^(n+1) − 1 calls for subsets, about e·n! for permutations.
  • Explain why answers must be copied when recorded, and what goes wrong if the unchoose step is missing.
  • Describe pruning and how to avoid duplicate answers when the input has repeated values.

Helpful before this lesson

  • M11 Recursion — Base cases, the call stack, recursion trees and the first look at memoization.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Mental model

To list every subset of {1, 2, 3}, make one decision per value: include it or not. Three yes/no decisions give 2 × 2 × 2 = 8 combinations, and you can draw them as a tree: the root is "nothing decided yet", each level decides one more value, and each of the 8 leaves is a finished subset.

Backtracking is a depth-first walk of that tree. It never builds the tree in memory. It keeps one partial answer (the current path from the root), and at every node it does three things:

  1. Choose: extend the partial answer with one option.
  2. Explore: recurse to make the remaining decisions.
  3. Unchoose: undo the extension, so the partial answer is exactly as it was before the choice.

Then it tries the next option at the same node. When no decisions are left, the partial answer is complete: record a copy.

In the lab, each node appears when its call starts and keeps its place: the layout is computed from the size of the full tree, so nothing moves as the search proceeds. The current node is highlighted, the nodes on the path to it are marked as waiting, and finished leaves carry their answer number.

Subsets: include, then skip

subsets(i, current):
    if i == n: record copy of current; return      # leaf: every value decided
    current.append(values[i])                       # choose: include values[i]
    subsets(i + 1, current)                         # explore
    current.pop()                                   # unchoose
    subsets(i + 1, current)                         # explore without values[i]

For [1, 2, 3] the answers come out as {1, 2, 3}, {1, 2}, {1, 3}, {1}, {2, 3}, {2}, {3}, {}: "include" is always explored before "skip". The tree has 2ⁿ leaves and 2ⁿ⁺¹ − 1 nodes in total, one call each (the Calls metric).

Permutations: pick any unused value next

A permutation decides "which value goes next" rather than "is this value in". At depth d there are n − d values left to choose from, so the tree branches n ways, then n − 1, …, then 1, and has n! leaves. A boolean array used remembers which values are already on the path:

permute(current, used):
    if len(current) == n: record copy of current; return
    for i in 0 .. n-1:
        if used[i]: continue                        # already on the path
        used[i] = true; current.append(values[i])   # choose
        permute(current, used)                      # explore
        current.pop(); used[i] = false              # unchoose

For [1, 2, 3] the six answers come out in index order: 123, 132, 213, 231, 312, 321. That is the same order as Python's itertools.permutations and as repeated std::next_permutation calls starting from sorted indices, which the tests use as references. The lab also counts the candidates rejected by used[i] (Skipped).

Why unchoose matters

The partial answer is shared by every call. When the "include 1" branch returns, current must be back to what it was, or the "skip 1" branch would start with a stale 1 in it. Unchoose is what makes one list serve the whole tree; it is also why the leaf records a copy: the list itself will keep changing, and storing a reference would leave you with n copies of whatever the list holds at the end (usually empty).

How much work

Generating Answers Calls (tree nodes) Time Extra space
Subsets of n 2ⁿ 2ⁿ⁺¹ − 1 O(n · 2ⁿ) O(n): path + stack
Permutations of n n! Σₖ n!/(n − k)! ≈ e · n! O(n · n!) O(n): path, used, stack

The n factor in the time is copying each answer (and, for permutations, scanning the used array at every node). The output itself has that size, so no algorithm that lists every answer can be asymptotically faster. The stack depth is only n + 1: like every depth-first search, backtracking holds one root-to-leaf path at a time. These are exponential and factorial costs: 20 values have about a million subsets, and 12 values already have 479,001,600 permutations. Backtracking is the right tool when you need every answer or when pruning cuts the tree down.

Pruning

Many problems ask for answers that satisfy a constraint: subsets whose sum is exactly T, placements of N queens where none attack each other. Backtracking checks the constraint as early as possible and returns without exploring a branch that cannot lead to a valid answer. With positive values sorted ascending, a subset-sum search can stop including values as soon as the running sum exceeds T, and every subtree below that point is never visited. Pruning does not change the worst case, but it often removes most of the tree in practice. The lab shows the unpruned trees so that every node is visible; the same choose, explore, unchoose skeleton gains one if for each rule.

Repeated values

With input [1, 1, 2] the code above produces {1, 2} twice (once with each 1) and permutation [1, 1, 2] twice. The lab therefore asks for distinct values. The standard fix is to sort the input, then skip a value at a given tree level if an equal value was already tried at that level. For permutations: if i > 0 and values[i] == values[i - 1] and not used[i - 1]: continue. For subsets, write the search as "choose the next value from position start onwards" and skip equal neighbours in that loop.

Language notes

  • C#: current.RemoveAt(current.Count - 1) undoes the choice; [.. current] copies the list.
  • Python: current.pop() and current.copy(). For the plain enumeration in production code, itertools.combinations and itertools.permutations are faster and lazy.
  • Java: current.remove(current.size() - 1) calls remove(int index). With a List<Integer>, remove(Integer.valueOf(x)) would instead remove by value: a classic mix-up.
  • C++: current.pop_back(); output.push_back(current) copies. std::next_permutation enumerates permutations in lexicographic order without recursion.

The teaching implementation

All four languages implement both searches with the same anchored lines as the lab. They read one shared fixture that fixes the exact order of the answers (empty input, one value, negatives, unsorted input, four values) and compare 300 random inputs of up to six values with a bitmask enumeration of subsets and with a permutation reference (itertools.permutations in Python, std::next_permutation in C++, a count-and-check in C# and Java).

Common mistakes

  • Recording current instead of a copy: every recorded answer ends up the same (usually empty).
  • Forgetting to unchoose, or undoing only half the choice (popping the list but leaving used[i] set): later branches start from a wrong state.
  • Unchoosing in the wrong place, for example after the second explore in the subset version.
  • Checking a constraint only at the leaves when it could prune much earlier.
  • Expecting distinct answers from repeated input without the sort-and-skip rule.

Edge cases

  • No values: the root is already a leaf, so there is exactly one answer, the empty subset (or the empty permutation). 2⁰ = 0! = 1.
  • One value: subsets {v} and {}; one permutation [v].

Worked practice

1. How many calls does the subset search make for n = 5, and how many answers?

Answer

2⁶ − 1 = 63 calls and 2⁵ = 32 answers: the leaves are half the nodes, plus one.

2. In the permutation search for [a, b, c, d], what is the 7th answer?

Answer

[b, a, c, d]. The first 3! = 6 answers start with a; the 7th is the first that starts with b, and the rest follow in index order.

3. You want all subsets of size exactly k. What can you prune?

Answer

Stop including once current has k values (every deeper "include" exceeds k), and stop when the values left are too few to reach k (len(current) + (n - i) < k). The search then visits only nodes on paths to the C(n, k) answers.

Summary

  • Backtracking = depth-first search of a decision tree with one shared partial answer.
  • Choose, explore, unchoose; record a copy at the leaves.
  • Subsets: 2ⁿ answers, 2ⁿ⁺¹ − 1 calls. Permutations: n! answers, about e·n! calls. Stack depth n + 1.
  • Pruning skips subtrees that cannot succeed; sorting plus a skip rule handles repeated values.

Full implementation

Subsets and permutations in four languages, each checked against one shared fixture that fixes the exact order of the answers (empty input, one value, negatives, unsorted input, four values) and 300 random inputs of up to six values compared with a bitmask enumeration of subsets and a brute-force or library permutation reference (itertools.permutations, std::next_permutation).

namespace Bekadan.Dsa.Examples.Backtracking;
 
/// <summary>
/// Backtracking over a decision tree: choose, explore, unchoose. One list holds the
/// partial answer and is copied only when an answer is complete.
/// Subsets: 2^n answers, O(n · 2^n) time. Permutations: n! answers, O(n · n!) time.
/// Both use O(n) extra space besides the output (the path plus the call stack).
/// With repeated values the answers repeat too; distinct values are assumed.
/// </summary>
public static class SubsetsAndPermutations
{
    public static List<List<int>> Subsets(IReadOnlyList<int> values)
    {
        var output = new List<List<int>>();
        CollectSubsets(values, 0, new List<int>(), output);
        return output;
    }
 
    private static void CollectSubsets(IReadOnlyList<int> values, int i, List<int> current, List<List<int>> output)
    {
        if (i == values.Count)
        {
            output.Add([.. current]); // a copy: current keeps changing
            return;
        }
        current.Add(values[i]);
        CollectSubsets(values, i + 1, current, output);
        current.RemoveAt(current.Count - 1);
        CollectSubsets(values, i + 1, current, output);
    }
 
    public static List<List<int>> Permutations(IReadOnlyList<int> values)
    {
        var output = new List<List<int>>();
        CollectPermutations(values, new List<int>(), new bool[values.Count], output);
        return output;
    }
 
    private static void CollectPermutations(IReadOnlyList<int> values, List<int> current, bool[] used, List<List<int>> output)
    {
        if (current.Count == values.Count)
        {
            output.Add([.. current]);
            return;
        }
        for (int i = 0; i < values.Count; i++)
        {
            if (used[i])
                continue;
            used[i] = true;
            current.Add(values[i]);
            CollectPermutations(values, current, used, output);
            current.RemoveAt(current.Count - 1);
            used[i] = false;
        }
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Backtracking/SubsetsAndPermutations.cs

"""Backtracking over a decision tree: choose, explore, unchoose.
 
One list holds the partial answer and is copied only when an answer is complete.
Subsets: 2**n answers, O(n * 2**n) time. Permutations: n! answers, O(n * n!) time.
Both use O(n) extra space besides the output (the path plus the call stack).
With repeated values the answers repeat too; distinct values are assumed.
"""
 
from collections.abc import Sequence
 
 
def subsets(values: Sequence[int]) -> list[list[int]]:
    output: list[list[int]] = []
    _collect_subsets(values, 0, [], output)
    return output
 
 
def _collect_subsets(values: Sequence[int], i: int, current: list[int], output: list[list[int]]) -> None:
    if i == len(values):
        output.append(current.copy())  # a copy: current keeps changing
        return
    current.append(values[i])
    _collect_subsets(values, i + 1, current, output)
    current.pop()
    _collect_subsets(values, i + 1, current, output)
 
 
def permutations(values: Sequence[int]) -> list[list[int]]:
    output: list[list[int]] = []
    _collect_permutations(values, [], [False] * len(values), output)
    return output
 
 
def _collect_permutations(values: Sequence[int], current: list[int], used: list[bool], output: list[list[int]]) -> None:
    if len(current) == len(values):
        output.append(current.copy())
        return
    for i in range(len(values)):
        if used[i]:
            continue
        used[i] = True
        current.append(values[i])
        _collect_permutations(values, current, used, output)
        current.pop()
        used[i] = False

Tested on CPython 3.14.0 · examples/python/dsa_examples/backtracking.py

package dev.bekadan.dsa.backtracking;
 
import java.util.ArrayList;
import java.util.List;
 
/**
 * Backtracking over a decision tree: choose, explore, unchoose. One list holds the
 * partial answer and is copied only when an answer is complete.
 * Subsets: 2^n answers, O(n · 2^n) time. Permutations: n! answers, O(n · n!) time.
 * Both use O(n) extra space besides the output (the path plus the call stack).
 * With repeated values the answers repeat too; distinct values are assumed.
 */
public final class SubsetsAndPermutations {
    private SubsetsAndPermutations() {
    }
 
    public static List<List<Integer>> subsets(int[] values) {
        List<List<Integer>> output = new ArrayList<>();
        collectSubsets(values, 0, new ArrayList<>(), output);
        return output;
    }
 
    private static void collectSubsets(int[] values, int i, List<Integer> current, List<List<Integer>> output) {
        if (i == values.length) {
            output.add(new ArrayList<>(current)); // a copy: current keeps changing
            return;
        }
        current.add(values[i]);
        collectSubsets(values, i + 1, current, output);
        current.remove(current.size() - 1);
        collectSubsets(values, i + 1, current, output);
    }
 
    public static List<List<Integer>> permutations(int[] values) {
        List<List<Integer>> output = new ArrayList<>();
        collectPermutations(values, new ArrayList<>(), new boolean[values.length], output);
        return output;
    }
 
    private static void collectPermutations(int[] values, List<Integer> current, boolean[] used, List<List<Integer>> output) {
        if (current.size() == values.length) {
            output.add(new ArrayList<>(current));
            return;
        }
        for (int i = 0; i < values.length; i++) {
            if (used[i]) {
                continue;
            }
            used[i] = true;
            current.add(values[i]);
            collectPermutations(values, current, used, output);
            current.remove(current.size() - 1); // remove(int index), not remove(Object)
            used[i] = false;
        }
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/backtracking/SubsetsAndPermutations.java

#pragma once
 
// Backtracking over a decision tree: choose, explore, unchoose. One vector holds the
// partial answer and is copied only when an answer is complete.
// Subsets: 2^n answers, O(n · 2^n) time. Permutations: n! answers, O(n · n!) time.
// Both use O(n) extra space besides the output (the path plus the call stack).
// With repeated values the answers repeat too; distinct values are assumed.
 
#include <cstddef>
#include <span>
#include <vector>
 
namespace bekadan::dsa {
 
namespace detail {
 
inline void collect_subsets(std::span<const int> values, std::size_t i, std::vector<int>& current, std::vector<std::vector<int>>& output) {
    if (i == values.size()) {
        output.push_back(current);  // a copy: current keeps changing
        return;
    }
    current.push_back(values[i]);
    collect_subsets(values, i + 1, current, output);
    current.pop_back();
    collect_subsets(values, i + 1, current, output);
}
 
inline void collect_permutations(std::span<const int> values, std::vector<int>& current, std::vector<bool>& used, std::vector<std::vector<int>>& output) {
    if (current.size() == values.size()) {
        output.push_back(current);
        return;
    }
    for (std::size_t i = 0; i < values.size(); ++i) {
        if (used[i]) continue;
        used[i] = true;
        current.push_back(values[i]);
        collect_permutations(values, current, used, output);
        current.pop_back();
        used[i] = false;
    }
}
 
}  // namespace detail
 
inline std::vector<std::vector<int>> subsets(std::span<const int> values) {
    std::vector<std::vector<int>> output;
    std::vector<int> current;
    detail::collect_subsets(values, 0, current, output);
    return output;
}
 
inline std::vector<std::vector<int>> permutations(std::span<const int> values) {
    std::vector<std::vector<int>> output;
    std::vector<int> current;
    std::vector<bool> used(values.size(), false);
    detail::collect_permutations(values, current, used, output);
    return output;
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/backtracking.hpp

References