Sub topic 6
Generating All Permutations
This chapter assumes you know the choose-explore-unchoose template and why results must be copied with path[:]. It also assumes you have seen the subsets generator. A permutation is an ordering of all the input elements. For [1, 2, 3] there are six: every way to line up the three values.
How Permutations Differ from Subsets
The subsets generator passes a start index so that each call only looks at later elements. That rule keeps [1, 2] and [2, 1] from both appearing, which is right for subsets. For permutations, order matters. After placing 2 first, you still need to be able to place 1 next. So the loop must scan the whole input at every level. It also has to skip elements that are already in the current path.
| Aspect | Subsets | Permutations |
|---|---|---|
| Loop range | `start` to end | whole input |
| Avoid reuse by | moving `start` forward | a `used` array |
| When to record | every node | only at full length |
| Number of results | 2^n | n! |
The State-Space Tree
Each level of the tree fixes one position in the ordering. The root has n branches, each child has n − 1, and so on. A leaf is a complete permutation.
The Implementation
def permutations(nums):
result = []
path = []
used = [False] * len(nums)
def backtrack():
if len(path) == len(nums):
result.append(path[:])
return
for i in range(len(nums)):
if used[i]:
continue
used[i] = True
path.append(nums[i])
backtrack()
path.pop()
used[i] = False
backtrack()
return result
print(permutations([1, 2, 3]))
# [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]The used array is a second piece of mutable state. Choosing an element now changes two things, used[i] and path. Unchoosing has to reverse both, in the opposite order. The used array marks indices, not values. That matters later when the input contains repeated values.
Common Errors
- Recording at every node. That copies the subsets pattern and returns partial orderings. Record only when
len(path) == len(nums). - Checking
nums[i] in path. This works for distinct values, but each check costs O(n), and it breaks on duplicates. Theusedarray is O(1) per check and tracks positions. - Appending
pathinstead ofpath[:]. Every stored result then points to the same list, which ends up empty.
Cost
There are n! leaves, and copying each one costs O(n), so the total time is O(n · n!). The recursion depth is n, and path and used take O(n) extra space, not counting the output. With n = 10 there are already 3,628,800 permutations, so this approach only works for small inputs.
Exercise
How many times is result.append called for nums = [1, 2, 3, 4], and how many total calls to backtrack happen (including the root call)?
Show answer
result.append runs 4! = 24 times, once per leaf. The total number of calls equals the number of tree nodes: 1 + 4 + 4·3 + 4·3·2 + 4·3·2·1 = 1 + 4 + 12 + 24 + 24 = 65.
Exercise
Modify the function to produce only permutations of length k (for example, all ordered pairs when k = 2). What single line changes?
Show answer
Change the base case to if len(path) == k: and add k as a parameter. For [1, 2, 3] with k = 2 the result is [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]].