Learn / Recursion and backtracking

Permutations

A permutation uses every element once, in some order. Build it position by position, choosing any unused element for the next place. With repeated letters, sort first and use equal letters only in their original order, so each arrangement appears once. When only the k-th permutation is wanted, count blocks of (n - 1)! instead of listing them.

How to recognise it

  • The question asks for every ordering, a specific ordering (the k-th), or the best ordering reachable by limited swaps.
  • n is small (about 8 to 10) when every ordering must be produced.

The idea in one picture

Fill a row of empty boxes from left to right. For the next box, pick any card you have not used yet. When every box is full, you have one permutation. Then take the last card back and try another.

Template

sort the letters
function build(cur):
    if cur is full: record it; return
    for i from 0 to n - 1:
        if used[i]: continue
        if i > 0 and c[i] == c[i - 1] and not used[i - 1]: continue   # repeats
        used[i] = true; add c[i]; build(cur); remove it; used[i] = false

The k-th permutation without listing

With n digits, each choice of first digit covers (n - 1)! permutations. Divide k - 1 by (n - 1)! to pick the first digit, keep the remainder, and repeat with the digits left. That is O(n²) instead of O(n!).

Common mistakes

  • Removing duplicates with a set after generating everything, which still does all the work.
  • Mixing 0-based and 1-based k in the k-th permutation.
  • Swapping greedily in "at most k swaps" problems, when equal best digits need every copy tried.

Problems

0 of 3 solved

Check yourself

How many permutations do 5 different letters have?

To find the 9th permutation of 1 2 3 4, how many permutations start with each first digit?

With sorted letters a a b, why skip a letter equal to the one before it when that one is unused?