Permutations visualization

Generate every ordering by choosing an unused element for each position, then undoing.

Build the permutation position by position. At each level, try every unused element, recurse, then mark it unused again so it can appear later in other branches.

Edge case: with duplicate values, sort first and skip an element equal to its previous sibling when that sibling is unused — this yields only distinct permutations.

Complexity

Time: best O(n·n!), average O(n·n!), worst O(n·n!). Space: O(n). Difficulty: Beginner.

Pseudocode

procedure permute(path):
  if |path| = n: output path; return
  for i ← 0 to n−1:
    if used[i]: continue
    if i > 0 and A[i] = A[i−1] and not used[i−1]: continue  // duplicate
    used[i] ← true; path.push(A[i])
    permute(path)
    path.pop(); used[i] ← false

More backtracking algorithms