![]() |
VOOZH | about |
Given an array arr[], generate all possible permutations of the elements in the array.
Note: All elements in the array are distinct.
Examples:
Input: arr[] = [1, 2, 3]
Output: [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
Explanation: There are 6 possible permutations (3! =6) of the array.Input: arr[] = [0]
Output: [[0]]
The idea is to fix one element at a time and recursively generate permutations for the rest. At each step, we swap the current element with another, explore further recursively, and then backtrack by swapping back.
We simply start at the first index, swap it with each possible choice, and recurse for the next index. After each recursive call, we backtrack by swapping back, so the array is restored for the next possibility. Repeating this until the end ensures every permutation is covered exactly once.
Base case: If idx == n, store the current arrangement as one valid permutation.
Recursive choices: For every index idx, we fix one element by swapping it with each element from idx to the last index.
1 2 3 1 3 2 2 1 3 2 3 1 3 2 1 3 1 2