Generate every subset and ordering with a clean recursive template.
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.
In this lesson you learn to list every subset and every ordering with a recursion that chooses, explores and undoes. You see how fast the lists grow, how to handle equal items, and how to stop when the list is too long to build.
You work on the release team of a social app. The settings screen has n toggles, and the onboarding has n steps. QA wants a test for every set of toggles, and a test for every order of the steps.
Your team lead says: How many tests is that, and can we generate them?
Here is a short check for 3 toggles: there are 8 sets, from none on to all on. For 3 steps there are 6 orders.
So the task is this: generate every set and every order, and learn how fast the lists grow.
A host seats guests in a row of chairs. The host picks a guest for the first chair, then one of the rest for the second chair, and so on. When the last chair is filled, the seating is one answer.
Then the host steps back. The last guest leaves the chair, and the host tries the next guest there. When no guest is left to try, the host steps back one more chair.
The host chooses, explores, and undoes. The same three words describe every recursion in this lesson.
A host seats guests row by row: choose a guest, explore the next chair, then undo and try another guest.
Before you write code, list the subsets of two toggles by hand. Decide toggle 1, then toggle 2, and skip a toggle before you take it.
Solve it by hand: The subsets of two flags. The hand-solve sheet loads in your browser.
Each call decides one toggle. A call that has decided every toggle saves the set it holds.
Each row is one call, in the order the calls start. A call on a toggle makes two calls: it skips the toggle, and then takes it.
| Call number | Call | Chosen so far | What it does |
|---|---|---|---|
| 1 | flag 1 | [] | skips, then takes |
| 2 | flag 2 | [] | skips, then takes |
| 3 | all decided | [] | saves [] |
| 4 | all decided | [2] | saves [2] |
| 5 | flag 2 | [1] | skips, then takes |
| 6 | all decided | [1] | saves [1] |
| 7 | all decided | [1, 2] | saves [1, 2] |
The four sets are [], [2], [1] and [1, 2]. The recursion made 7 calls for 2 toggles.
Start with a correct version for the orders. It tries every tuple of steps, and keeps a tuple only if no step repeats.
def all_orders(n):
found = []
for steps in product(range(1, n + 1), repeat=n): # every tuple of n steps
if len(set(steps)) == n: # keep it only if no step repeats
found.append(list(steps))
return foundThis is correct. The team keeps it as the reference. The question is how it behaves when n grows.
Now check the real size.
The onboarding can have up to 10 steps.
Run the function, in Python, and look at the numbers:
Predict the waste
Q For 8 steps the first attempt checks 16,777,216 tuples and keeps 40,320. About how many tuples does it check for each order it keeps?
Answer: C
The number of tuples is 8 to the power 8, and the orders are 8 factorial. The ratio is 416.1, so almost every tuple is thrown away.
The first attempt is correct, and most of its work is wasted. The orders can be built without ever making a tuple that repeats a step.
Build the subsets with a recursion. Each call decides one item: it skips the item first, and then takes it. Look at the calls for 3 toggles as a tree.
Three toggles make a tree of 15 calls with 8 leaves, and each leaf is one subset.
The tree for 3 toggles has 15 calls and 8 leaves. Each leaf is a set of choices, and so one subset. In general the tree has 2^(n+1) - 1 calls and 2^n leaves.
The orders have a different tree. The first position has 3 choices, the second has 2, and the third has 1. The tree for 3 steps has 16 calls: 1 + 3 + 6 + 6. It has 6 leaves, one for each order.
Now compare how the answers grow. Every number below is the count of results that a template returned, or the formula that the counts follow.
| n | Subsets, 2^n | Orderings, n! |
|---|---|---|
| 1 | 2 | 1 |
| 2 | 4 | 2 |
| 3 | 8 | 6 |
| 4 | 16 | 24 |
| 5 | 32 | 120 |
| 6 | 64 | 720 |
| 8 | 256 | 40,320 |
| 10 | 1,024 | 3,628,800 |
For 20 items there are 1,048,576 subsets and 2,432,902,008,176,640,000 orders. For 30 items there are 1,073,741,824 subsets. The size of the answer is the lower bound for the cost of any method.
Race: Subsets and orderings of n items, counted by running the templates. The operation counter loads in your browser.
The race counts the results of the two templates for 4 to 9 items. For 9 items the orderings are 362,880 and the subsets are 512.
The call is all_subsets(3). The player stops at five steps and asks you to predict.
Dry run: Predict each step: the subsets of three flags. The step-by-step player loads in your browser.
Reading without the player? Cover the last column and predict it row by row. The row is the subset that a call saves, in order.
| Subset number | Subset | Calls so far |
|---|---|---|
| 1 | [] | 4 |
| 2 | [3] | 5 |
| 3 | [2] | 7 |
| 4 | [2, 3] | 8 |
| 5 | [1] | 11 |
| 6 | [1, 3] | 12 |
| 7 | [1, 2] | 14 |
| 8 | [1, 2, 3] | 15 |
The first subset is the empty one, because every flag is skipped first. The last is all three flags.
The number of calls is about twice the number of results for subsets, and about 2.7 times for orders. The cost of generating is the size of the answer, up to a constant. No clever code can make it smaller.
Here is the rule that keeps the answers correct. Every line of the templates exists to protect it.
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.
The list is shared by every call. A call changes it before it explores. It must change it back afterwards, or the next branch starts from the wrong state.
A saved answer is a copy. If the call saves the list itself, every saved answer is the same list, and it ends up in the final state.
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.
Decide each item in turn. A call skips the item and explores, takes it and explores, and then undoes the take.
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;
}Rebuild the template: put its lines back in order. Loads in your browser.
The skip comes first, so the empty subset comes first and the full set comes last. The answer for n = 3 is the eight sets of the dry run.
Exercise · Predict the output: Which pairs come out, and in what order?. The skip-or-take recursion runs for 4 flags, and keeps only the subsets of exactly 2 flags. What does it print?
found = []
def walk(flag, chosen):
if flag > 4:
if len(chosen) == 2:
found.append("".join(map(str, chosen)))
return
walk(flag + 1, chosen)
chosen.append(flag)
walk(flag + 1, chosen)
chosen.pop()
walk(1, [])
print(" ".join(found))The subset template skips the flag, takes it, and undoes the take, so the caller sees the list as it was.
Fill the positions one by one. A mark says which items are placed, so a call tries only unused items.
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;
}The loop tries the items in input order. So the orderings come out in a fixed order: the one that uses the earlier items first comes first.
The ordering template marks an unused item, explores the next position, and then clears the mark.
A different way to choose swaps the item at i into the current position. It needs no marks, because the items before the position are fixed.
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;
}The swap template lists the same orders in a different sequence. For the items 1, 2 and 3, the marks version lists the orders 123, 132, 213, 231, 312, 321. The swap version lists 123, 132, 213, 231, 321, 312.
Exercise · Find the bug: The ordering that finds no orders. This swap version should list every ordering, but for the items [1, 2] it returns nothing. Which line is wrong?
def all_orders_by_swap(items):
found = []
arrange(list(items), 0, found)
return found
def arrange(items, position, found):
if position == len(items):
found.append(list(items))
return
for i in range(position + 1, len(items)):
items[position], items[i] = items[i], items[position]
arrange(items, position + 1, found)
items[position], items[i] = items[i], items[position]A review panel is a set of exactly 10 reviewers from 20. Use the skip-or-take template, and stop a call when the panel is full, or when too few reviewers remain to fill it. Each count below was measured by running the function.
| Recursion for 20 reviewers and panels of 10 | Calls | Panels found |
|---|---|---|
| Skip or take, every subset, then keep size 10 | 2,097,151 | 184,756 |
| Skip or take, stop at size 10 and when the panel cannot be filled | 537,471 | 184,756 |
Both versions find 184,756 panels, which is the number of ways to choose 10 of 20. The second one cuts branches that cannot lead to a panel, and makes about a quarter of the calls. The next lesson builds on that idea.
Exercise · Put it in order: Count the panels. Arrange the lines into a function that counts the panels of k reviewers that can be chosen from n, by skipping or taking the last reviewer.
def count_panels(n, k):
if k == 0:
return 1
if n < k:
return 0
skip = count_panels(n - 1, k)
take = count_panels(n - 1, k - 1)
return skip + take
return count_panels(n - 1, k) + count_panels(n, k - 1)Real production data brings edge cases.
With 0 toggles there is exactly one subset: the empty one. all_subsets(0) returns [[]]. The base case answers it, and no call is made on a flag.
With the items [7] there are 2 subsets, [] and [7], and 1 ordering, [7]. The recursion makes 3 calls for the subsets and 2 calls for the ordering.
The items [1, 1, 2] have 6 orderings from the marks template, but only 3 different ones: [[1, 1, 2], [1, 2, 1], [2, 1, 1]]. Swapping the places of two equal items gives the same ordering again. The items [1, 2, 2] have 8 subsets, but only 6 different ones.
For n = 20 there are 1,048,576 subsets, and 2,432,902,008,176,640,000 orderings. The orderings overflow a 32-bit integer, and they fill about a quarter of a 64-bit one. Never build the whole list when you need a page or a count.
This version adds the flag, but never removes it after the call.
Counterexample: for 3 flags the third subset comes out as [3, 2], not [2]. The flag 3 stays in the list from the previous branch.
Every choice needs its undo, in the same call that made it.
Without the undo, the third subset of three flags is 3, 2 instead of 2, because a flag stays in the list.
This version saves chosen, and not a copy of it.
Counterexample: for 2 flags it returns [[], [], [], []]. All four saved lists are the same list, and it is empty at the end.
Save a copy when you keep an answer.
This version of the swap template leaves the items swapped after the call.
Counterexample: for the items [1, 2, 3] it returns 6 lists, but only 4 are different. The lists [1, 2, 3] and [1, 3, 2] each come out twice, and [2, 1, 3] and [2, 3, 1] are missing.
Swap back in the same call, after the explore step.
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.
Choose, explore and undo is for jobs where every answer must be seen. For a count, a best answer or a yes or no, a formula or a table usually wins.
Your team lead brings four product changes. Each one uses the same three steps.
QA wants a test for every set of toggles. That is Template 1 (LeetCode 78: Subsets).
QA wants a test for every order of the onboarding steps. That is Template 2 or 3 (LeetCode 46: Permutations).
A moderation tool picks a panel of 10 from 20. Choose in increasing order, and stop when the panel is full (LeetCode 77: Combinations).
Two onboarding steps are the same screen. Sort the steps and skip an equal unused step (LeetCode 47: Permutations II).
Exercise · Break it: Find the steps this count gets wrong. This counts the different orders of the steps, and skips a step that equals the one before it. Find a list of steps where the count is wrong.
def count_orders(items):
items = sorted(items)
used = [False] * len(items)
return place(items, used, 0)
def place(items, used, placed):
if placed == len(items):
return 1
total = 0
for i in range(len(items)):
if used[i]:
continue
if i > 0 and items[i] == items[i - 1]:
continue
used[i] = True
total += place(items, used, placed + 1)
used[i] = False
return totalExplain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate how you list every subset and every ordering, and why a call must undo its choice. The AI tutor checks your answer against the invariant and the key points of this lesson.
Here is how you could explain it in an interview, now that you have built it.
For subsets I decide each item in turn. I skip it and explore, take it and explore, and then undo the take. The tree has 2^n leaves.
For orderings I fill positions one by one, with an item that is not used yet. I mark it, explore, and then clear the mark. The tree has n! leaves.
Every call must restore what it changed, and I save a copy of the list, not the list itself. For equal items, I sort and skip an equal sibling.
To list every subset, I decide each item in turn. A call skips the item and explores, takes it and explores, and then undoes the take. When every item is decided, I save a copy of the list. There are two to the n subsets.
To list every ordering, I fill the positions one by one. I try each item that is not used yet: I mark it, explore, and then clear the mark. There are n factorial orderings.
The cost is the size of the answer, so I check it first. Thirty items have a billion subsets. When the list is too long, I stop as soon as a page is full.
For equal items, I sort them and skip an item equal to the one tried before it at the same step.
Checkpoint · Subsets and permutations
Q1/10 How do you list every subset of n items with a recursion?
Answer: B
Each call decides one item. It skips the item and explores, then takes it and explores, then undoes the take. A call that has decided every item saves a copy.
Q2/10 How many calls does the skip-or-take recursion make for 3 items, and how many subsets does it find?
Answer: B
The tree has 2^(3+1) - 1 = 15 calls and 2^3 = 8 leaves. Every leaf is one subset, and the other calls are the decisions above them.
Q3/10 For 8 steps, the first attempt checks 8^8 tuples and keeps the orderings. About how many tuples does it check for each ordering?
Answer: C
There are 16,777,216 tuples and 40,320 orderings. The ratio is about 416, so almost every tuple is thrown away.
Q4/10 How does the ordering template avoid tuples that repeat an item?
Answer: B
The marks say which items are placed. A call tries only unused items, so no repeated item is ever placed.
Q5/10 How many orderings do 10 items have?
Answer: C
10 factorial is 3,628,800. Subsets double with each item, but orderings multiply by a growing number.
Q6/10 A subset recursion adds a flag to the list, explores, and never removes it. For 3 flags, what happens?
Answer: B
Without the undo, the flag stays in the list. The third subset comes out as [3, 2], and it should be [2].
Q7/10 Why must a call save a copy of the list, and not the list itself?
Answer: B
The same list is shared by every call. If it is saved without a copy, all saved answers point to the one list, which ends up in its final state.
Q8/10 The items [1, 1, 2] have 6 orderings from the marks template. How many are different, and how do you avoid the repeats?
Answer: A
Equal items repeat answers: 3 orderings are different. Sorting puts equal items together, and skipping an equal item whose twin is unused removes the repeats without losing any answer.
Q9/10 A job needs one page of the subsets of 40 items, at position 100,000. What is the best plan?
Answer: B
The recursion lists the subsets in order, so it can stop when the page is full. For this page it made 200,265 calls, while 2^40 is 1,099,511,627,776.
Q10/10 When is choose-explore-undo the wrong tool?
Answer: B
A count needs no list. The skip-or-take recursion makes 2,097,151 calls for 20 items, and the formula 2^20 = 1,048,576 needs none.
Ten questions on this lesson. Pass with 80% or more to be sure the idea has landed before the next lesson.
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | All feature flag combinations | Platform | Easy | Skip or take, undo, and stopping when a page is full |
| 2 | All orderings of a pipeline | Observe | Medium | Marks for used items, and the order of the output |
| 3 | Subsets without repeats in the input | Chat | Medium | Sorting and skipping an equal sibling |
| 4 | Choose k reviewers from n | Feed | Medium | Choosing in increasing order, with a bound that cuts dead calls |
| 5 | Orderings with repeated stages | Freight | Medium | Skipping an equal unused sibling in orderings |
Review cards from this lesson.
Five cards from this lesson join your spaced-review deck. The first one comes back tomorrow.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Step through it.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.