#46

Permutations

Medium Backtracking with used[]

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return all orderings of an array of distinct integers.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: every ordering of distinct numbers.

Why this works: fill positions one by one with any unused number; undo after exploring.

Example: [1, 2, 3]

1 → 2 → 3, 1 → 3 → 22 → 1 → 3, 2 → 3 → 13 → 1 → 2, 3 → 2 → 1

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Forgetting to unmark used[i] after the recursive call.

Solve on LeetCode ↗
Complexity
  • Time: O(n · n!).
  • Space: O(n).
Topic: Recursion & Backtracking
🎬 Episodes 29–36: video coming soon