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 of distinct integers, return every subset of it, in any order. A subset is any selection of the numbers, from none of them to all of them, and the order inside a subset does not matter. The answer must not contain the same subset twice. The list of all subsets is also called the power set.

Example 1
Input: nums = [1, 2, 3]
Output: [[], [1], [2], [1,2], [3], [1,3], [2,3], [1,2,3]]
Explanation: 23 = 8 subsets, including the empty one.
Example 2
Input: nums = [0]
Output: [[], [0]]
Solution

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.

The choice tree for [1, 2, 3]. From the empty subset, branches add 1, add 2 and add 3. From [1], branches add 2 and add 3; from [1, 2], add 3 gives [1, 2, 3]; from [2], add 3 gives [2, 3]. A dashed branch add 1? from [2] is not built, because [2, 1] is [1, 2]. [3] has no branches. Orange numbers show the order the eight subsets are saved.

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 nums, which the program does not know in advance. Instead, one method, build, handles one box. It saves the subset of that box, then for each number it may add, it adds the number and calls itself to handle the box below.

Because build calls itself for each box under its own, it is a recursive method. The calls go as deep as the tree does: four levels for [1, 2, 3], from [ ] down to [1, 2, 3].

Building each subset once

How does build know which numbers it may add? It receives a position, start, the first index in nums it may use. The top box gets 0, so all three numbers are allowed. When a call adds nums[i], the call for the box below gets i + 1, so only later numbers remain. That is why the box [2] offers only add 3: the 2 sits at index 1, so the call below it starts at index 2.

Saving a subset

When is a subset ready for the answer? Every box in the picture is one, so build saves its subset first thing, before it adds anything. The subset is kept in one list, named subset, that the whole search shares and keeps changing. So the answer gets a copy, new ArrayList<>(subset), which stays as it is when subset changes later.

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, build removes the number it just added, with subset.remove(subset.size() - 1). The shared list is then the same as before that choice, and the loop tries the next number. This removal is the "taking it off" step of backtracking.

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, mask, run from 0 to 2n - 1, one value per subset. Reading bit 0 as the rightmost digit, put nums[i] in the subset when bit i of mask is 1.

For [1, 2, 3], a mask of 5 is 101 in binary. Bits 0 and 2 are set, so it picks nums[0] and nums[2], which gives [1, 3]. Bit Manipulation Basics shows more of using a number's bits as a set.

Java Solution

The method subsets works in these steps:

  1. First, subsets creates the answer list, result, and calls build with start set to 0 and an empty list subset. This first call is the top box of the tree, [ ].
  2. Each call of build begins by adding a copy of subset to result, so every call saves one subset.
  3. Then a loop moves i from start to the end of nums. For each i, it adds nums[i] to subset and calls build with i + 1, so the call below may only use later numbers.
  4. When that call returns, build removes the last number from subset, and the loop goes on to the next i.
  5. When the first call to build has finished, subsets returns result.

The main method runs both examples, an empty array and the two numbers [-4, 7], and then prints how many subsets four numbers give.

Java
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:

Output
[[], [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]] follows the orange numbers in the picture, not the order of Example 1. Both are correct, since the subsets may come in any order.

The empty array prints [[]], one subset with nothing in it. The first call still saves the empty subset before its loop finds no number to add. The pair [-4, 7] gives four subsets, and the last line shows 16 for four numbers, which is 24.

The i + 1 in the recursive call matters. Passing start + 1 instead lets the call below reuse the number just added or go back to earlier ones. On [1, 2, 3] that version returns 16 lists, among them [2, 2] and [3, 2]. Saving subset itself instead of a copy goes wrong too: the answer holds eight references to the one shared list, which is empty when the search ends, so it prints eight empty lists.

Complexity

The search makes one call of build per subset, and each call copies the subset it saves.

  • Time: O(n ยท 2n), because build runs once for each of the 2n subsets of the n numbers, and copying a subset into result takes up to n steps.
  • Space: O(n) besides the output, because the calls go at most n + 1 deep, one level per number added, and the shared subset list never holds more than the n numbers.

When the input can contain equal values, see Subsets II.