AlgoVerse

Generating all permutations

Build all n! permutations of 1 to n in lexicographic order: add an unused item, recurse, then take it back.

Fill the permutation one place at a time. For each empty place, try every item not used yet, fill the rest (recursively), then take the item back to try the next one: backtracking.

Read the full explanation ↓
Input:
n=3PDF export

Three items: 3! = 6 permutations, in the order 123, 132, 213, 231, 312, 321.

  1. def permutations(n):
  2. items = list(range(1, n + 1))
  3. used = [False] * n
  4. current = []
  5. rows = []
  6. extend(items, used, current, rows)
  7. return len(rows)
  8. def extend(items, used, current, rows):
  9. if len(current) == len(items):
  10. rows.append(tuple(current))
  11. return
  12. for i in range(len(items)):
  13. if used[i]:
  14. continue
  15. used[i] = True
  16. current.append(items[i])
  17. extend(items, used, current, rows)
  18. current.pop()
  19. used[i] = False

Invariant: current is always a prefix of the remaining permutations, and used marks exactly its items.

Start

current—

The table is still empty.

Recursion tree

Filled orange = running call · Orange outline = still on the stack · Grey = finished

Local variables

n3

Orange = changed in this step

Call stack

  1. permutations()line 1
Step 1 of 211
Black = found · Orange = key stepchoose: 0/15 · found: 0/6 · undo: 0/15
    Explanation

    The idea

    Fill the permutation one place at a time. For each empty place, try every item not used yet, fill the rest (recursively), then take the item back to try the next one: backtracking.

    If the items are tried in order, the permutations come out in lexicographic order.

    Cost

    n! permutations of n items each: O(n · n!). That grows very fast (10! = 3628800), which is why n is at most 4 here.

    What to watch in the trace

    • The call tree is the state-space tree: each path from the root to a leaf is one permutation.
    • If you only need the next permutation (without building them all), see the "next permutation" page.