Problem
Given an array nums
of distinct integers, return all the possible permutations. You can return the answer in any order.
Example 1:
Input: nums = [1,2,3] Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Example 2:
Input: nums = [0,1] Output: [[0,1],[1,0]]
Example 3:
Input: nums = [1] Output: [[1]]
Intuition
The task is to find all possible permutations of a given array nums containing distinct integers. A permutation is an arrangement of elements in a specific order. The solution involves using a recursive approach to generate all possible permutations.
Approach
Initialize Result List:
Create an empty list res to store the resulting permutations.
Base Case:
If the length of the array nums is 1, return a list containing a single permutation (the array itself).
Recursive Permutation:
Iterate over each element in the array nums.
For each element, remove it from the array, recursively generate permutations for the remaining elements, and append the current element to each generated permutation.
Extend the result list res with the permutations obtained.
Return Result:
Return the final result res.
Complexity
- Time complexity:
The time complexity is O(n!), where n is the number of elements in the array. This is because there are n! possible permutations.
- Space complexity:
The space complexity is O(n!), as there are n! permutations, each with a length of n. The space required for the recursion stack also contributes to the space complexity.
Code
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res = []
if len(nums) == 1:
return [nums.copy()]
for _ in range(len(nums)):
n = nums.pop(0)
perms = self.permute(nums)
for perm in perms:
perm.append(n)
res.extend(perms)
nums.append(n)
return res