Algorithms Playbook
PatternTime O(n · n!) · Space O(n)8 min read

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".

Permutations: pick what goes next
Speed
011223

path

0∅

saved permutations

0∅
[]each level picks which number goes in that position
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 return
8 for i in range(len(nums)):
9 if used[i]:
10 continue
11 used[i] = True
12 path.append(nums[i])
13 dfs()
14 path.pop()
15 used[i] = False
16 dfs()
17 return res
3 numbers: 3! = 6 permutations. At each level we try every number that is not used yet.

Variables

path[]
saved0
Step 1/59· Calls: 1
Same choose / explore / undo skeleton as subsets. What changes is the choice: here each level picks one of the numbers that is not used yet, tracked with a `used` array.

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
SubsetsNo2ⁿIn or out
Combinations of kNon! / (k!(n−k)!)Which next item (only later ones)
PermutationsYesn!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