Permutations: every ordering with backtracking
Same choose / explore / undo skeleton as subsets, but now the choice is which unused element goes next. The `used` array, the n! count and when to stop.
In short
To build every ordering, fill positions one by one: at each position try every element not used yet, recurse, then undo. There are n! permutations, so it only works for small n.
The idea: fill the slots one at a time
With [1, 2, 3], pick the first number (3 options), then the second (2 options left), then the last (1 option): 3 × 2 × 1 = 6 permutations. Every level of the tree picks "what goes in the next slot".
path
saved permutations
1def permutations(nums):2 res, path = [], []3 used = [False] * len(nums)4 def dfs():5 if len(path) == len(nums):6 res.append(path[:])7 return8 for i in range(len(nums)):9 if used[i]:10 continue11 used[i] = True12 path.append(nums[i])13 dfs()14 path.pop()15 used[i] = False16 dfs()17 return res
Variables
Tracking what's taken
A `used` array
used[i]says whether nums[i] is in the path- Set it on choose, clear it on undo
- Simple, works for any input
Swapping in place
- Swap the chosen element into position
start - No extra array, a bit trickier to get right
- Swap back to undo
Subsets vs permutations vs combinations
| Order matters? | How many (n items) | Choice per level | |
|---|---|---|---|
| Subsets | No | 2ⁿ | In or out |
| Combinations of k | No | n! / (k!(n−k)!) | Which next item (only later ones) |
| Permutations | Yes | n! | Any unused item |
Combinations avoid repeats by only choosing items after the current index (pass a start). Permutations choose from all unused items, so order produces different results.
Key takeaways
- 01Permutations fill positions one by one, trying every unused element.
- 02Mark on choose, unmark on undo: the used array is the state.
- 03There are n! of them: only feasible for small n.
- 04Combinations use a start index to avoid reordering the same set.
Check your understanding
1 of 3
How many permutations do 4 distinct numbers have?
Related topics
Subsets & combinations
When a problem asks for all the ways to do something, walk a tree of choices with recursion: choose → explore → undo. For subsets each number is either in or out, so the tree has 2ⁿ leaves.
9 min read →Recursion
A recursive function solves a problem by calling itself on a smaller version of it, until it reaches a base case it can answer directly. Each pending call waits on the call stack, so recursion costs memory too.
8 min read →