Generate subsets
Beginner · 8 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Generating subsets lists every way to pick some items from a group, including none and all. For each item you decide "take it" or "skip it", and backtracking walks through every combination of those decisions in an orderly way.
Practical use cases
- Web app: Testing every combination of feature flags. A team has 4 feature flags and wants to test every on-off combination before release. Generating all 16 subsets gives the full test checklist, so no odd mix such as flag A on and B off is forgotten. The checklist is generated by code, so adding a fifth flag simply doubles the list instead of needing someone to write it out.
- Web app: Bundle deals on a shop page. A shop wants to show which sets of 3 or 4 accessories fit a customer's budget. Generating every subset of the cart items and filtering by total price produces the bundle suggestions.
- Web app: Permission combinations. An admin screen has permissions such as read, write, delete and export. Listing every subset shows all possible role types so the team can decide which ones really make sense. Security reviewers can then cross out the combinations that make no sense, such as delete without read, and keep the real role types.
- System: Brute-force puzzle solvers. Small puzzle solvers, such as picking numbers that add to a target, simply try every subset, which is fine for 15 to 20 items.
The story: The Tiffin Box Choices
Mira's mother had packed three things for the school picnic: a samosa, a laddoo and a banana. But Mira's tiffin box was small, and she could not decide what to carry. "Let me list every possible lunch," she said, pencil ready.
First she wrote the full box. Then she wrote the box without the banana. Then without the laddoo, then... she lost count and wrote the same lunch twice. Kabir peeked over: "You are guessing. Make it a rule. For each food ask one question: take it, or leave it?"
Together they walked the questions in order. Samosa: take. Laddoo: take. Banana: take. That is one lunch. Now go back one step and flip the last answer: Banana: leave. Another lunch. Back up again, flip the laddoo... Kabir never had to remember old answers, he only walked back and changed the last one.
They got exactly 8 lunches, including the lunch with nothing in the box. That walk, choose, explore, un-choose, is called backtracking, and listing all subsets is its friendliest first example.
How to spot this problem, and where you need it
You must examine every possible selection from a small set of items, for testing, suggestions or exact puzzles, and you do not want to miss any or repeat any.
Signs you need it
- The wording says "all possible combinations", "every selection", "power set" or "all subsets".
- For each item the choice is simply in or out, and you need to see every mix.
- The set is small, up to about 20 items, because each extra item doubles the number of results.
Where to use it in a project
- QA tools that exercise every on-off mix of settings or flags.
- Bundle, coupon or add-on pickers that search for sets matching a budget or rule.
The solution
Write a function that takes the current position and the list chosen so far. At each position make two calls: one that skips the item, and one that adds it to the chosen list. When the position passes the last item, record a copy of the chosen list. After the "add" call returns, remove the item again (the backtrack step) so the list is ready for the next branch. Every possible subset appears exactly once.
Payoff: Before: forgetting 3 of the 16 flag combinations and shipping a bug. After: all 16 are generated and checked automatically.
Explain it like I am 8
You have 3 toys and want every way to carry some of them to a friend's house. For each toy you just say "yes, bring it" or "no, leave it". Say yes to everything first, write it down, then go back and change your last answer. Keep going back and changing until you have tried every yes/no mix.
How it works, step by step
- Keep a current list (what you have taken so far) and look at one item at a time, starting at position 0.
- Base case: if you have decided about every item, save a copy of the current list.
- Choose: put the item in the current list and explore the rest of the items.
- Un-choose: remove that item again (this is the "back" in backtracking).
- Explore the rest of the items without that item. Both branches are now done.
The code in four languages
PHP
<?php
// Return every subset of $items using choose / explore / un-choose.
function subsets(array $items): array {
$result = [];
$current = [];
$explore = function (int $i) use (&$explore, &$result, &$current, $items) {
if ($i === count($items)) {
$result[] = $current; // decided about everything: save a copy
return;
}
$current[] = $items[$i]; // choose: take the item
$explore($i + 1);
array_pop($current); // un-choose: put it back
$explore($i + 1); // explore again without the item
};
$explore(0);
return $result;
}
foreach (subsets([1, 2, 3]) as $s) {
echo '{' . implode(', ', $s) . "}\n";
}JavaScript
// Return every subset of items using choose / explore / un-choose.
function subsets(items) {
const result = [];
const current = [];
function explore(i) {
if (i === items.length) {
result.push([...current]); // decided about everything: save a copy
return;
}
current.push(items[i]); // choose: take the item
explore(i + 1);
current.pop(); // un-choose: put it back
explore(i + 1); // explore again without the item
}
explore(0);
return result;
}
for (const s of subsets([1, 2, 3])) {
console.log('{' + s.join(', ') + '}');
}Java
import java.util.*;
public class Main {
// Return every subset of items using choose / explore / un-choose.
static List<List<Integer>> subsets(int[] items) {
List<List<Integer>> result = new ArrayList<>();
explore(items, 0, new ArrayList<>(), result);
return result;
}
static void explore(int[] items, int i, List<Integer> current, List<List<Integer>> result) {
if (i == items.length) {
result.add(new ArrayList<>(current)); // decided about everything: save a copy
return;
}
current.add(items[i]); // choose: take the item
explore(items, i + 1, current, result);
current.remove(current.size() - 1); // un-choose: put it back
explore(items, i + 1, current, result); // explore again without the item
}
public static void main(String[] args) {
for (List<Integer> s : subsets(new int[]{1, 2, 3})) {
StringJoiner sj = new StringJoiner(", ", "{", "}");
for (int x : s) sj.add(String.valueOf(x));
System.out.println(sj);
}
}
}Go
package main
import (
"fmt"
"strconv"
"strings"
)
// subsets returns every subset of items using choose / explore / un-choose.
func subsets(items []int) [][]int {
var result [][]int
var current []int
var explore func(i int)
explore = func(i int) {
if i == len(items) {
result = append(result, append([]int(nil), current...)) // decided about everything: save a copy
return
}
current = append(current, items[i]) // choose: take the item
explore(i + 1)
current = current[:len(current)-1] // un-choose: put it back
explore(i + 1) // explore again without the item
}
explore(0)
return result
}
func main() {
for _, s := range subsets([]int{1, 2, 3}) {
parts := []string{}
for _, x := range s {
parts = append(parts, strconv.Itoa(x))
}
fmt.Println("{" + strings.Join(parts, ", ") + "}")
}
}Time: O(n × 2^n) · Extra space: O(n). Every item doubles the number of subsets, and copying each one costs up to n. The recursion itself is only n levels deep.
Watch out for
- Saving
currentitself instead of a copy. It keeps changing, so every saved subset ends up looking the same (empty!). - Forgetting to un-choose (the
pop). The leftover items leak into the next branch. - Expecting a specific order. The order depends on whether you explore "take" or "skip" first.
Quick check
- How many subsets does a list of 4 different items have?
- 4
- 8
- 16
- 24
- Why do we remove the item after exploring?
- To save memory in the result
- To sort the answer
- So the next branch starts clean, without that item
- What should be stored in the result list at the base case?
- A copy of the current list
- The index i
- The original items