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
Example 1
Output: [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
Example 2
Output: [[0, 1], [1, 0]]
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.
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, buildbuildbuild
When does it stop? The numbers placed so far sit in a list named permpermnumsbuildperm
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 numsnumsusedused[i]nums[i]perm
Checking perm.contains(nums[i])perm
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 permused[i]
Swapping numbers in place (optional)
Is the usednumsposnums[pos]pospos + 1
Java Solution
The method permutebuild
- First,
creates the listpermute and callsresult with an empty listbuild and a boolean arrayperm as long asused , all false.nums - In
, check whetherbuild equalsperm.size() . If it does, add a copy,nums.length , tonew ArrayList<>(perm) and return. The copy is needed becauseresult keeps changing afterwards.perm - Otherwise, a
loop movesfor over every index ofi and skipsnums wheni is true.used[i] - For an unused index, set
to true, appendused[i] tonums[i] , and callperm to fill the next position.build - When that call returns, remove the last number from
and setperm back to false, so the loop can try the next index.used[i] - When the first call of
returns,build returnspermute .result
The main
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:
[[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]]
Look at the last line. Four numbers give 24 orderings, which is 4 × 3 × 2 × 1. The orderings follow the order of nums
Both undo lines matter. With perm.removeused[i] = false[[1, 2, 3]]perm[[], [], [], [], [], []]
Complexity
The work is copying the n! complete orderings, where n is the number of values in nums
- Time: O(n · n!), because each of the n! orderings is copied in n steps, and the calls of
, fewer than 3 × n! in all (16 for three numbers, 65 for four), each loop at most once over the n indexes.build - Space: O(n) besides the output, because the calls go at most n + 1 deep, one per position plus the one that saves, and
andperm hold at most n entries each.used
n! grows quickly: 10 numbers already have 3,628,800 orderings. If nums[1, 1, 2]