Subsets
List every subset of an array of distinct numbers, each one exactly once, by adding numbers in array order and undoing each choice.
Given an array nums
Example 1
Output: [[], [1], [2], [1,2], [3], [1,3], [2,3], [1,2,3]]
Explanation: 23 = 8 subsets, including the empty one.
Example 2
Output: [[], [0]]
The Idea
Imagine a sandwich bar with three fillings, numbered 1, 2 and 3. You can order any mix of them: no filling, one, two or all three. How many different sandwiches is that? Example 1 lists them: the empty one, three with one filling, three with two, and one with all three, eight in total.
Each filling is either in or out, so every filling doubles the count: 2 ร 2 ร 2 = 8 for three numbers, and 2n for n numbers. Writing them down by hand, you would also take care not to write [2, 1] after [1, 2], because a sandwich with 2 and 1 is the same as one with 1 and 2. So how can a program list all of them, each exactly once, however long the array is?
A tidy way is to build each subset in the order the numbers appear in the array. Start with the empty subset. Add one number to it, and after a number, allow only numbers that come later in the array. Look at the picture below.
Each box is a subset, and each line labelled add 1, add 2 or add 3 leads to the subset with that number added. From [1], the branches are add 2 and add 3. From [2], only add 3 is left: the dashed line marked add 1? is not followed, because [2, 1] is [1, 2], which already sits under [1]. The box [3] has no branches at all, since no number comes after 3.
The small orange numbers give the order in which the eight subsets are saved. The search first goes as deep as it can: [ ], [1], [1, 2], [1, 2, 3]. Then it takes 3 off, takes 2 off, and adds 3 instead, which gives [1, 3]. Adding a filling, listing every subset that grows from it, then taking it off again to try the next filling is called backtracking.
Notice that every box is a subset for the answer, not only the boxes at the bottom. Even the top box, [ ], counts: it is the empty subset.
Solution Approach
Turning the tree into code means settling four things: how to walk the tree, how to build each subset once, when to save a subset, and how to step back after a choice. There is also an optional way without the tree, which counts in binary.
Walking the tree
How does a program walk the tree in the picture? For three numbers you could write three loops, one inside the other, but the number of loops would have to match the length of numsbuild
Because build[1, 2, 3]
Building each subset once
How does buildstartnumsnums[i]i + 1
Saving a subset
When is a subset ready for the answer? Every box in the picture is one, so buildsubsetnew ArrayList<>(subset)subset
Stepping back after a choice
How does the search get from [1, 2, 3] back up to [1] and on to [1, 3]? After the call for the box below returns, buildsubset.remove(subset.size() - 1)
Counting in binary (optional)
Is there a way without recursion? Each number is either in or out, and the binary digits (bits) of a whole number can record exactly that. Let a counter, masknums[i]imask
For [1, 2, 3]masknums[0]nums[2]
Java Solution
The method subsets
- First,
creates the answer list,subsets , and callsresult withbuild set to 0 and an empty liststart . This first call is the top box of the tree, [ ].subset - Each call of
begins by adding a copy ofbuild tosubset , so every call saves one subset.result - Then a loop moves
fromi to the end ofstart . For eachnums , it addsi tonums[i] and callssubset withbuild , so the call below may only use later numbers.i + 1 - When that call returns,
removes the last number frombuild , and the loop goes on to the nextsubset .i - When the first call to
has finished,build returnssubsets .result
The main[-4, 7]
import java.util.ArrayList;
import java.util.List;
public class Subsets {
public static List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
build(nums, 0, new ArrayList<>(), result);
return result;
}
private static void build(int[] nums, int start, List<Integer> subset,
List<List<Integer>> result) {
result.add(new ArrayList<>(subset)); // every call saves a subset
for (int i = start; i < nums.length; i++) {
subset.add(nums[i]); // choose nums[i]
build(nums, i + 1, subset, result); // later numbers only: no repeats
subset.remove(subset.size() - 1); // undo, to try the next number
}
}
public static void main(String[] args) {
System.out.println(subsets(new int[] {1, 2, 3}));
System.out.println(subsets(new int[] {0}));
System.out.println(subsets(new int[] {}));
System.out.println(subsets(new int[] {-4, 7}));
System.out.println(subsets(new int[] {5, 1, 9, 2}).size() + " subsets of [5, 1, 9, 2]");
}
}
Running it prints:
[[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]
[[], [0]]
[[]]
[[], [-4], [-4, 7], [7]]
16 subsets of [5, 1, 9, 2]
Look at the first line: [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]
The empty array prints [[]]subset[-4, 7]
The i + 1start + 1[1, 2, 3][2, 2][3, 2]subset
Complexity
The search makes one call of build
- Time: O(n ยท 2n), because
runs once for each of the 2n subsets of the n numbers, and copying a subset intobuild takes up to n steps.result - Space: O(n) besides the output, because the calls go at most n + 1 deep, one level per number added, and the shared
list never holds more than the n numbers.subset
When the input can contain equal values, see