Permutations
Master this topic with zero to advance depth.
Permutations
Exploration vs. Selection
In permutation problems, the goal is to arrange all elements of a set in every possible order. Unlike combinations, the order matters here ([1, 2] is different from [2, 1]).
Key Backtracking Strategies
- Visited Array: Maintain a boolean array to track which elements are already included in the current permutation. This is intuitive but uses extra space.
- Swap-Based: Swap the current element with every element to its right, recurse, and then swap back. This is highly efficient as it uses the input array for state.
Given an array nums of distinct integers, return all possible permutations. Includes visual state-space tree.
Examples
Level I: Backtracking with Visited Array
Intuition
Maintain a list of 'remaining' elements or a boolean array to track usage.
Iterate through all numbers. If a number is not visited, add it to the current permutation, mark it visited, and recurse. Unmark and remove after recursion.
Detailed Dry Run
Dry Run: nums=[1,2]
| Path | Visited | Action |
| :--- | :--- | :--- |
| [] | {F, F} | Start |
| [1] | {T, F} | Choose 1 |
| [1,2] | {T, T} | Choose 2 (Result!) |
| [1] | {T, F} | Backtrack |
| [] | {F, F} | Backtrack |
| [2] | {F, T} | Choose 2 |
| [2,1] | {T, T} | Choose 1 (Result!) |Level II: Backtracking with Swapping (In-Place)
Intuition
Instead of a visited array, we can rearrange the input array itself to represent the current state.
At index first, swap nums[first] with every element from first to N-1. Recurse for first + 1. This 'fixes' one element and permutes the rest.
Detailed Dry Run
nums=[1,2,3], first=0
- Swap(0,0): nums=[1,2,3]. Recurse first=1. 2. Swap(1,1): nums=[1,2,3]. Recurse first=2. SUCCESS [1,2,3]. 3. Swap(1,2): nums=[1,3,2]. Recurse first=2. SUCCESS [1,3,2].
- Swap(0,1): nums=[2,1,3]. Recurse first=1...
Level III: Iterative Lexicographical Order
Intuition
Generate permutations in lexicographical order. This is useful when the input is sorted or we need to find the 'next' permutation.
Start with the smallest permutation (sorted). Repeatedly find the next lexicographical permutation until we return to the start.
Detailed Dry Run
nums=[1,2,3]
- Initial: [1,2,3]
- Next: [1,3,2]
- Next: [2,1,3]
- Next: [2,3,1]
- Next: [3,1,2]
- Next: [3,2,1]
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.