Algorithm · Recursion and backtracking · O(n · 2ⁿ) subsets, O(n · n!) permutations

Backtracking

Build a solution one choice at a time, explore, then undo the choice: subsets and permutations as a walk over a decision tree.

The full derivation, edge cases and exercises are in the lesson Backtracking: subsets and permutations on a decision tree. Open it full width in the playground.

On this page
  1. The idea
  2. Steps
  3. Invariants
  4. Complexity
  5. When to use it
  6. Step through it
  7. Implementation
  8. Learn more
  9. References

The idea

Backtracking is depth-first search over the space of partial solutions. At each level you choose an option, recurse, and unchoose it so the next option starts from the same state. Pruning cuts branches that cannot lead to a valid answer, but the worst case still grows exponentially.

Steps

  1. If the partial solution is complete, record it.
  2. For each remaining option: choose it, recurse, then undo it.

Invariants

What holds at every step; the correctness argument rests on these.

  • On return from a call, the shared state is exactly what it was before the call.
  • Each leaf of the decision tree is produced once.

Complexity

Backtracking complexity
CaseTimeExtra space
All subsetsO(n · 2ⁿ)O(n) stack + output
All permutationsO(n · n!)O(n) stack + output

When to use it

Use it when

  • You must enumerate or search combinations, arrangements or assignments, especially with constraints that prune early.

Avoid it when

  • Subproblems repeat: dynamic programming reuses their answers.
  • n is large and only a count or an optimum is needed.

Step through it

The interactive lab for backtracking: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.

Implementation in four languages

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

Learn more

Data structures it uses

Problems, patterns and exercises

References