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

Backtracking

Subsets and permutations as choose, explore, unchoose on a decision tree.

The full explanation, derivation and practice are in the lesson Backtracking: subsets and permutations on a decision tree.

Implementation

The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.

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