Generating subsets
32 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A subset of an array is any selection of its elements where order does not matter—from the empty list [] up to the full array itself. The collection of all 2ⁿ subsets is called the power set, and learning the two ways to generate it gives you the exact template used for combinations and knapsack-style search.
Include or exclude
A subset is any selection of elements from a set, including none or all of them. A set of n elements has 2^n subsets.
The most direct way to think about subsets of nums is one index at a time. Standing at index i, you have exactly two choices: either include nums[i] in the current subset, or exclude nums[i] and move on to i + 1.
This builds a complete binary state space tree of depth n. Every leaf at depth i == nums.length is one complete subset, so there are 2ⁿ leaves in total. For nums = [1, 2], index 0 branches into [1] (include 1) and [] (exclude 1); index 1 then branches each of those into [1, 2], [1], [2], and [].
- Base case: When
index == nums.length, we have made an include/exclude decision for every element. Addnew ArrayList<>(current)toresultsandreturn. - Branch 1 (Exclude): Call
backtrack(nums, index + 1, current, results)without changingcurrent. - Branch 2 (Include): Add
nums[index]tocurrent, callbacktrack(nums, index + 1, current, results), and then remove the last element (current.remove(current.size() - 1)) to un-choose.
Predict the output
Include or exclude?
Each call either includes a[i] or skips it. Pick what each program prints.
Round 1 of 2
The array is {1, 2}. The include call comes first.
The loop-based version
There is a second way to organize the exact same 2ⁿ subsets that connects directly to combinations and combination-sum problems. Instead of asking "Do I include nums[i]?", ask "Which element after my current position should I pick next?"
Example 1 · Include / Exclude vs Loop-Based Subsets
import java.util.ArrayList;import java.util.List;
public class SubsetsTwoWays { // Approach 1: Include / Exclude binary decision tree public static List<List<Integer>> subsetsIncludeExclude(int[] nums) { List<List<Integer>> results = new ArrayList<>(); includeExclude(nums, 0, new ArrayList<>(), results); return results; }
private static void includeExclude(int[] nums, int idx, List<Integer> cur, List<List<Integer>> res) { if (idx == nums.length) { res.add(new ArrayList<>(cur)); return; } // Exclude nums[idx] includeExclude(nums, idx + 1, cur, res); // Include nums[idx] cur.add(nums[idx]); includeExclude(nums, idx + 1, cur, res); cur.remove(cur.size() - 1); }
// Approach 2: Loop-based with start index public static List<List<Integer>> subsetsLoop(int[] nums) { List<List<Integer>> results = new ArrayList<>(); backtrackLoop(nums, 0, new ArrayList<>(), results); return results; }
private static void backtrackLoop(int[] nums, int start, List<Integer> cur, List<List<Integer>> res) { res.add(new ArrayList<>(cur)); // Every node is a valid subset! for (int i = start; i < nums.length; i++) { cur.add(nums[i]); backtrackLoop(nums, i + 1, cur, res); cur.remove(cur.size() - 1); } }
public static void main(String[] args) { int[] nums = {1, 2, 3}; System.out.println("Include/Exclude: " + subsetsIncludeExclude(nums)); System.out.println("Loop-based: " + subsetsLoop(nums)); }}Include/Exclude: [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]] Loop-based: [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]
What this code does
- Both methods produce the exact same 8 subsets (2³ = 8), just in a different traversal order.
- In
includeExclude, subsets are recorded only at the leaves (idx == nums.length). - In
backtrackLoop, every node of the tree recordsnew ArrayList<>(cur)upon entry, so there are 2ⁿ nodes in total instead of 2ⁿ⁺¹ - 1 nodes.
In this loop-based version, every node in the state space tree—not just the leaves—is already a valid subset! At the very start of backtrack(nums, start, current, results), you immediately record new ArrayList<>(current). Then you loop i from start to nums.length - 1: choose nums[i], recurse with i + 1 (so you only ever pick later elements and never revisit earlier ones), and un-choose nums[i]. Passing i + 1 guarantees that [1, 2] is generated once and [2, 1] is never generated.
results) and O(n) auxiliary stack space. The loop-based version is the one you will use most often because it makes skipping duplicate values effortless.Subsets with duplicates
What if the input contains duplicate numbers, such as nums = [1, 2, 2]? The plain loop generates [1, 2] twice: once using the first 2 (at index 1) and once using the second 2 (at index 2).
Example 2 · Subsets II: Handling Duplicate Elements with Sorting
import java.util.ArrayList;import java.util.Arrays;import java.util.List;
public class SubsetsWithDuplicates { public static List<List<Integer>> subsetsWithDup(int[] nums) { Arrays.sort(nums); // Step 1: Group duplicates together List<List<Integer>> results = new ArrayList<>(); backtrack(nums, 0, new ArrayList<>(), results); return results; }
private static void backtrack(int[] nums, int start, List<Integer> current, List<List<Integer>> results) { results.add(new ArrayList<>(current)); for (int i = start; i < nums.length; i++) { // Step 2: Skip duplicate choice at the SAME tree level if (i > start && nums[i] == nums[i - 1]) { continue; } current.add(nums[i]); backtrack(nums, i + 1, current, results); current.remove(current.size() - 1); } }
public static void main(String[] args) { int[] nums = {2, 1, 2}; System.out.println("Unique subsets of [2, 1, 2]: " + subsetsWithDup(nums)); }}Unique subsets of [2, 1, 2]: [[], [1], [1, 2], [1, 2, 2], [2], [2, 2]]
What this code does
- Sorting
[2, 1, 2]gives[1, 2, 2], placing both2s at indices1and2. - When
currentis[1]andstart == 1:i = 1picks the first2to form[1, 2], and inside that recursive call (start == 2),i = 2satisfiesi == start, so the second2is picked to form[1, 2, 2]. - After backtracking to
current = [1](start == 1), the loop advances toi = 2. Nowi > start(2 > 1) andnums[2] == nums[1], socontinueskips picking the second2as a duplicate[1, 2].
Yet [1, 2, 2]—which uses both 2s—is completely valid and must be kept! The fix has two parts. First, sort nums so equal numbers sit side by side. Second, inside the for (int i = start; i < nums.length; i++) loop, skip nums[i] if it equals nums[i - 1] and we are on the same decision level (i > start):
- When
i == start, we are picking the first child of the current recursive call—so even ifnums[i] == nums[i - 1], we keep it. That is what allows[1, 2, 2](index 1 is chosen at depth 1, and index 2 is chosen as the first optioni == startat depth 2). - When
i > startandnums[i] == nums[i - 1], it means we just finished exploring the entire subtree wherenums[i - 1]was chosen at this exact slot, and we backtracked. Pickingnums[i]in the very same slot would build an identical subtree, so wecontinue.
Bitmask version preview
When n is small (n ≤ 20) and all elements are distinct, you can also generate all 2ⁿ subsets without recursion by counting mask from 0 to (1 << n) - 1.
Example 3 · Bitmask Preview: Generating All Subsets Iteratively
import java.util.ArrayList;import java.util.List;
public class SubsetsBitmask { public static List<List<Integer>> subsetsByMask(int[] nums) { int n = nums.length; int total = 1 << n; // 2^n subsets List<List<Integer>> results = new ArrayList<>(total);
for (int mask = 0; mask < total; mask++) { List<Integer> subset = new ArrayList<>(); for (int j = 0; j < n; j++) { if ((mask & (1 << j)) != 0) { subset.add(nums[j]); } } results.add(subset); } return results; }
public static void main(String[] args) { int[] nums = {10, 20, 30}; List<List<Integer>> all = subsetsByMask(nums); for (int mask = 0; mask < all.size(); mask++) { String bits = String.format("%3s", Integer.toBinaryString(mask)).replace(' ', '0'); System.out.println("mask " + bits + " -> " + all.get(mask)); } }}mask 000 -> [] mask 001 -> [10] mask 010 -> [20] mask 011 -> [10, 20] mask 100 -> [30] mask 101 -> [10, 30] mask 110 -> [20, 30] mask 111 -> [10, 20, 30]
What this code does
- Each integer
maskfrom0(000in binary) to7(111in binary) corresponds to one unique subset of the 3 elements. (mask & (1 << j)) != 0checks whether the j-th bit ofmaskis1; if so,nums[j]is included.
Each integer mask has n binary bits: if bit j is 1 ((mask & (1 << j)) != 0), include nums[j] in that subset. We will study bitmasks in detail in the next module, Bit Manipulation & Math Basics, where bit operations shine.
Next step
Check your understanding
10 quick questions