
Sponsored
Sponsored
This approach uses recursion combined with backtracking to generate all possible permutations of the input array. The algorithm works by swapping elements of the array and recursively building permutations by fixing one element at a time until the entire array is permutated.
Time Complexity: O(n * n!) as there are n! permutations and we copy each permutation.
Space Complexity: O(n!) for storing the permutations, plus additional space used by the recursive stack.
1def permute(nums):
2 def backtrack(first=0):
3 if first == n:
4 output.append(nums[:])
5 for i in range(first, n):
6 nums[first], nums[i] = nums[i], nums[first]
7 backtrack(first + 1)
8 nums[first], nums[i] = nums[i], nums[first]
9
10 n = len(nums)
11 output = []
12 backtrack()
13 return output
14
15print(permute([1, 2, 3]))
16This Python implementation uses a recursive backtracking approach to generate the permutations. It swaps the elements to fix elements at each recursive level and then backtracks to get back to the previous state.
An alternative iterative approach utilizes a queue to generate permutations level by level by inserting each number at every possible position within every possible permutation.
Time Complexity: O(n * n!), iterating through permutations.
Space Complexity: O(n!) for storing permutations, constant space for current permutation array.
1from itertools
This Python solution uses the itertools.permutations function that directly generates permutations using combinatorial generation, simplifying implementation.