Generate every subset and ordering with a clean recursive template.
Each call restores the shared list and marks exactly as it found them, and saves a copy of the list when it keeps an answer.
Use it when you must list every subset, ordering or choice that follows a rule. Signal words: every subset, every ordering, all combinations.
Choose: change the shared list or marks by one choice.
Explore: call the same function for the next decision.
Undo: restore what you changed. Save a copy, not the list, when you keep an answer.
Cost: the answer size, 2^n for subsets and n! for orderings, times the work to copy one answer.
def all_subsets(n):
found = []
walk(n, 1, [], found)
return found
def walk(n, flag, chosen, found):
# [1] Base case: every flag is decided, so the chosen flags are one subset. Keep a copy.
if flag > n:
found.append(list(chosen))
return
# [2] Skip the flag, and explore the rest.
walk(n, flag + 1, chosen, found)
# [3] Take the flag, and explore the rest.
chosen.append(flag)
walk(n, flag + 1, chosen, found)
# [4] Undo the choice, so the caller sees the list as it was.
chosen.pop()public int[][] allSubsets(int n) {
List<int[]> found = new ArrayList<>();
walk(n, 1, new ArrayList<>(), found);
return found.toArray(new int[0][]);
}
private void walk(int n, int flag, List<Integer> chosen, List<int[]> found) {
// [1] Base case: every flag is decided, so the chosen flags are one subset. Keep a copy.
if (flag > n) {
found.add(chosen.stream().mapToInt(Integer::intValue).toArray());
return;
}
// [2] Skip the flag, and explore the rest.
walk(n, flag + 1, chosen, found);
// [3] Take the flag, and explore the rest.
chosen.add(flag);
walk(n, flag + 1, chosen, found);
// [4] Undo the choice, so the caller sees the list as it was.
chosen.remove(chosen.size() - 1);
}void walk(int n, int flag, vector<int>& chosen, vector<vector<int>>& found) {
// [1] Base case: every flag is decided, so the chosen flags are one subset. Keep a copy.
if (flag > n) {
found.push_back(chosen);
return;
}
// [2] Skip the flag, and explore the rest.
walk(n, flag + 1, chosen, found);
// [3] Take the flag, and explore the rest.
chosen.push_back(flag);
walk(n, flag + 1, chosen, found);
// [4] Undo the choice, so the caller sees the list as it was.
chosen.pop_back();
}
vector<vector<int>> allSubsets(int n) {
vector<vector<int>> found;
vector<int> chosen;
walk(n, 1, chosen, found);
return found;
}function walk(n, flag, chosen, found) {
// [1] Base case: every flag is decided, so the chosen flags are one subset. Keep a copy.
if (flag > n) {
found.push(chosen.slice());
return;
}
// [2] Skip the flag, and explore the rest.
walk(n, flag + 1, chosen, found);
// [3] Take the flag, and explore the rest.
chosen.push(flag);
walk(n, flag + 1, chosen, found);
// [4] Undo the choice, so the caller sees the list as it was.
chosen.pop();
}
function allSubsets(n) {
const found = [];
walk(n, 1, [], found);
return found;
}def all_orders(items):
found = []
build(items, [False] * len(items), [], found)
return found
def build(items, used, order, found):
# [1] Base case: every item is placed, so the order is one answer. Keep a copy.
if len(order) == len(items):
found.append(list(order))
return
for i in range(len(items)):
if not used[i]:
# [2] Choose the unused item: mark it and add it to the order.
used[i] = True
order.append(items[i])
# [3] Explore the next position.
build(items, used, order, found)
# [4] Undo the choice: remove the item and clear its mark.
order.pop()
used[i] = Falsepublic int[][] allOrders(int[] items) {
List<int[]> found = new ArrayList<>();
build(items, new boolean[items.length], new ArrayList<>(), found);
return found.toArray(new int[0][]);
}
private void build(int[] items, boolean[] used, List<Integer> order, List<int[]> found) {
// [1] Base case: every item is placed, so the order is one answer. Keep a copy.
if (order.size() == items.length) {
found.add(order.stream().mapToInt(Integer::intValue).toArray());
return;
}
for (int i = 0; i < items.length; i++) {
if (!used[i]) {
// [2] Choose the unused item: mark it and add it to the order.
used[i] = true;
order.add(items[i]);
// [3] Explore the next position.
build(items, used, order, found);
// [4] Undo the choice: remove the item and clear its mark.
order.remove(order.size() - 1);
used[i] = false;
}
}
}void build(const vector<int>& items, vector<bool>& used, vector<int>& order, vector<vector<int>>& found) {
// [1] Base case: every item is placed, so the order is one answer. Keep a copy.
if (order.size() == items.size()) {
found.push_back(order);
return;
}
for (size_t i = 0; i < items.size(); i++) {
if (!used[i]) {
// [2] Choose the unused item: mark it and add it to the order.
used[i] = true;
order.push_back(items[i]);
// [3] Explore the next position.
build(items, used, order, found);
// [4] Undo the choice: remove the item and clear its mark.
order.pop_back();
used[i] = false;
}
}
}
vector<vector<int>> allOrders(const vector<int>& items) {
vector<vector<int>> found;
vector<bool> used(items.size(), false);
vector<int> order;
build(items, used, order, found);
return found;
}function build(items, used, order, found) {
// [1] Base case: every item is placed, so the order is one answer. Keep a copy.
if (order.length === items.length) {
found.push(order.slice());
return;
}
for (let i = 0; i < items.length; i++) {
if (!used[i]) {
// [2] Choose the unused item: mark it and add it to the order.
used[i] = true;
order.push(items[i]);
// [3] Explore the next position.
build(items, used, order, found);
// [4] Undo the choice: remove the item and clear its mark.
order.pop();
used[i] = false;
}
}
}
function allOrders(items) {
const found = [];
build(items, new Array(items.length).fill(false), [], found);
return found;
}def all_orders_by_swap(items):
found = []
arrange(list(items), 0, found)
return found
def arrange(items, position, found):
# [1] Base case: every position is fixed, so the list is one answer. Keep a copy.
if position == len(items):
found.append(list(items))
return
for i in range(position, len(items)):
# [2] Choose: swap the item at i into the current position.
items[position], items[i] = items[i], items[position]
# [3] Explore the next position.
arrange(items, position + 1, found)
# [4] Undo the choice: swap the two items back.
items[position], items[i] = items[i], items[position]public int[][] allOrdersBySwap(int[] items) {
List<int[]> found = new ArrayList<>();
arrange(items.clone(), 0, found);
return found.toArray(new int[0][]);
}
private void arrange(int[] items, int position, List<int[]> found) {
// [1] Base case: every position is fixed, so the list is one answer. Keep a copy.
if (position == items.length) {
found.add(items.clone());
return;
}
for (int i = position; i < items.length; i++) {
// [2] Choose: swap the item at i into the current position.
int held = items[position];
items[position] = items[i];
items[i] = held;
// [3] Explore the next position.
arrange(items, position + 1, found);
// [4] Undo the choice: swap the two items back.
held = items[position];
items[position] = items[i];
items[i] = held;
}
}void arrange(vector<int>& items, int position, vector<vector<int>>& found) {
// [1] Base case: every position is fixed, so the list is one answer. Keep a copy.
if (position == (int)items.size()) {
found.push_back(items);
return;
}
for (int i = position; i < (int)items.size(); i++) {
// [2] Choose: swap the item at i into the current position.
swap(items[position], items[i]);
// [3] Explore the next position.
arrange(items, position + 1, found);
// [4] Undo the choice: swap the two items back.
swap(items[position], items[i]);
}
}
vector<vector<int>> allOrdersBySwap(const vector<int>& items) {
vector<vector<int>> found;
vector<int> work = items;
arrange(work, 0, found);
return found;
}function arrange(items, position, found) {
// [1] Base case: every position is fixed, so the list is one answer. Keep a copy.
if (position === items.length) {
found.push(items.slice());
return;
}
for (let i = position; i < items.length; i++) {
// [2] Choose: swap the item at i into the current position.
[items[position], items[i]] = [items[i], items[position]];
// [3] Explore the next position.
arrange(items, position + 1, found);
// [4] Undo the choice: swap the two items back.
[items[position], items[i]] = [items[i], items[position]];
}
}
function allOrdersBySwap(items) {
const found = [];
arrange(items.slice(), 0, found);
return found;
}This version adds the flag, but never removes it after the call.
This version saves chosen, and not a copy of it.
This version of the swap template leaves the items swapped after the call.
If you need only how many subsets there are, do not list them. The skip-or-take recursion makes 2,097,151 calls for 20 items, and 2^20 is 1,048,576. A formula gives it at once.
systemdesignmastery.dev/dsa/cheatsheets/subsets-and-permutations