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
kin the k-th permutation. - Swapping greedily in "at most k swaps" problems, when equal best digits need every copy tried.
Problems
- Print all the permutations of the given stringmediumguide ready
- Find Maximum number possible by doing at-most K swapsmediumguide ready
- Permutation Sequencehardguide ready