Permutations

List every ordering of an array of distinct numbers by filling one position at a time and undoing each choice.

Given an array nums of distinct integers, so no number appears twice, return every possible ordering of its numbers. An ordering that uses each number exactly once is called a permutation. The orderings can be returned in any order.

Example 1
Input: nums = [1, 2, 3]
Output: [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
Example 2
Input: nums = [0, 1]
Output: [[0, 1], [1, 0]]
Solution

The Idea

Three books on a shelf, numbered 1, 2 and 3, can stand in six different orders: 1 2 3, 1 3 2, 2 1 3, 2 3 1, 3 1 2 and 3 2 1. Example 1 asks for exactly these six orderings.

How would you list them by hand without missing one or writing one twice? Most people fill the shelf from the left. The first position can take any of the three books. Once a book stands there, the second position has two books left, and the third position has one. That gives 3 × 2 × 1 = 6 orderings. For n numbers the count is n × (n - 1) × ... × 1, written n! and read "n factorial".

Drawing every choice as a box under the choice before it gives a tree, here called the choice tree. Look at the picture below. Each box holds the number put in one position, and the rows are labelled first position, second position and third position.

The choice tree for [1, 2, 3]. From nothing chosen yet, the first position takes 1, 2 or 3. Under 1, the second position skips 1 because it is already used and takes 2 or 3, and the third position takes the number left, giving [1, 2, 3] and [1, 3, 2]. Under 2 and under 3 the same steps give the other four orderings.

Follow the orange path: 1 goes in the first position, then 2, then 3, which ends in the complete ordering [1, 2, 3]. To find the next ordering, take the 3 back out, then the 2, so that only 1 is on the shelf again. The other choice for the second position is 3, which leads to [1, 3, 2] in the teal box.

Now look at the dashed box labelled "skipped: 1 is already used". Under 1, the second position may not take 1 again, because that book already stands in the first position. With 2 or with 3 in the first position, the same steps give the four orderings in the boxes labelled "same steps give".

So a program can list every ordering by walking this tree. Each step down puts one number in the next free position. Each step back up takes the last number out again, so the position can try its next number. Going down one choice and then undoing it to try the next one, as from [1, 2, 3] back to 1 and on to [1, 3, 2], is called backtracking.

Solution Approach

Turning the tree into code means settling three things: how one position gets filled, how the code knows which numbers are in use, and how a choice gets undone. Swapping numbers inside the array is an optional variant of the second and third.

Filling one position per call

Why not write one loop per position, one inside the other? For [1, 2, 3] that is three loops, but four numbers would need four, and the code cannot change its own number of loops. So one method, build, fills a single position and then calls itself to fill the next one. In the picture, each box is one call of build, and each line down from it is a call it makes. A method like build, which fills the first position and then asks itself to fill the second, is called recursive.

When does it stop? The numbers placed so far sit in a list named perm. Once perm holds as many numbers as nums, every position is filled, so build saves a copy of perm and returns. For [1, 2, 3] that makes 16 calls in all: one with nothing placed, three with one number placed, six with two, and six that save a complete ordering.

Knowing which numbers are in use

Which numbers may go in the next position? Any number not yet on the shelf, even one that sits earlier in nums. So every call loops over all the indexes of nums, and a boolean array used marks the ones taken: used[i] is true while nums[i] is in perm. Checking it is a single lookup. For [1, 2, 3], the calls skip 15 indexes this way, the dashed box in the picture being one of them.

Checking perm.contains(nums[i]) would also work, because the numbers are distinct, but it walks through perm on every check.

Undoing a choice

What happens when the call for the next position returns? The choice is undone in two parts: the last number is removed from perm, and used[i] goes back to false. Then the loop tries the next index for the same position. In the picture, after [1, 2, 3] is saved, 3 and then 2 come back out, and the call at the box 1 moves on to 3.

Swapping numbers in place (optional)

Is the used array needed at all? A variant keeps the numbers already placed at the front of nums itself. To fill position pos, it swaps each number from nums[pos] to the end into position pos in turn, calls itself for pos + 1, and swaps back. This saves the boolean array, but the orderings come out a little differently: for [1, 2, 3], the last two are [3, 2, 1] and then [3, 1, 2].

Java Solution

The method permute and its helper build work in these steps:

  1. First, permute creates the list result and calls build with an empty list perm and a boolean array used as long as nums, all false.
  2. In build, check whether perm.size() equals nums.length. If it does, add a copy, new ArrayList<>(perm), to result and return. The copy is needed because perm keeps changing afterwards.
  3. Otherwise, a for loop moves i over every index of nums and skips i when used[i] is true.
  4. For an unused index, set used[i] to true, append nums[i] to perm, and call build to fill the next position.
  5. When that call returns, remove the last number from perm and set used[i] back to false, so the loop can try the next index.
  6. When the first call of build returns, permute returns result.

The main method runs both examples and a single number, then lists the orderings of 4, 3, 2, 1 and prints how many there are, with the first and the last.

Java
import java.util.ArrayList;
import java.util.List;

public class Permutations {

    public static List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        build(nums, new boolean[nums.length], new ArrayList<>(), result);
        return result;
    }

    private static void build(int[] nums, boolean[] used, List<Integer> perm,
                              List<List<Integer>> result) {
        if (perm.size() == nums.length) {
            result.add(new ArrayList<>(perm));  // a copy: perm keeps changing
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (used[i]) {
                continue;                       // already in this ordering
            }
            used[i] = true;                     // choose
            perm.add(nums[i]);
            build(nums, used, perm, result);    // fill the next position
            perm.remove(perm.size() - 1);       // undo the choice
            used[i] = false;
        }
    }

    public static void main(String[] args) {
        System.out.println(permute(new int[] {1, 2, 3}));
        System.out.println(permute(new int[] {0, 1}));
        System.out.println(permute(new int[] {5}));
        List<List<Integer>> four = permute(new int[] {4, 3, 2, 1});
        System.out.println(four.size() + " orderings, first " + four.get(0)
            + ", last " + four.get(four.size() - 1));
    }
}

Running it prints:

Output
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
[[0, 1], [1, 0]]
[[5]]
24 orderings, first [4, 3, 2, 1], last [1, 2, 3, 4]

The six orderings of [1, 2, 3] come out in the same order as the choice tree, from the orange [1, 2, 3] and the teal [1, 3, 2] through to [3, 2, 1]. The line [[5]] shows that a single number has one ordering: the first call puts 5 in the one position, and the next call saves it.

Look at the last line. Four numbers give 24 orderings, which is 4 × 3 × 2 × 1. The orderings follow the order of nums, not the size of the numbers: [4, 3, 2, 1] comes first because the loop always tries index 0 first, and its reverse, [1, 2, 3, 4], comes last.

Both undo lines matter. With perm.remove kept but used[i] = false left out, each number stays marked after its first use, and [1, 2, 3] gives only [[1, 2, 3]]. Saving perm itself instead of a copy gives [[], [], [], [], [], []]: all six entries are the same list, which is empty once every choice has been undone.

Complexity

The work is copying the n! complete orderings, where n is the number of values in nums, plus the calls on the way down to them.

  • Time: O(n · n!), because each of the n! orderings is copied in n steps, and the calls of build, fewer than 3 × n! in all (16 for three numbers, 65 for four), each loop at most once over the n indexes.
  • Space: O(n) besides the output, because the calls go at most n + 1 deep, one per position plus the one that saves, and perm and used hold at most n entries each.

n! grows quickly: 10 numbers already have 3,628,800 orderings. If nums had equal numbers, this code would repeat orderings, for example [1, 1, 2] twice for the input [1, 1, 2]. Permutations II lists each ordering once.