Introduction
Permutations means:
- generating all possible arrangements
- of array elements
Unlike subsets:
- order matters
Example:
Input:1 2 3
Output:
[1,2,3]
[1,3,2]
[2,1,3]
[2,3,1]
[3,1,2]
[3,2,1]
Explanation:
Every arrangement of elements is generated.This problem is one of the most important applications of:
Backtracking Constraints
1 <= Array Size <= 8Approach : Backtracking Solution
Explanations:
Explanation:
The idea is:
- choose unused element
- place it in current permutation
Steps:
- Start with empty permutation.
- Choose unused element.
- Add element.
- Recurse further.
- Backtrack and remove element.
This approach:
- explores all arrangements
- generates all permutations
Dry Run
Array:
1 2 3
Choose 1:
[1]
Choose 2:
[1,2]
Choose 3:
[1,2,3]
Backtrack:
[1,2]
Backtrack:
[1]Continue remaining permutations...