46. Permutations
Given a collection of distinct integers, return all possible permutations.
Approach: Backtracking
Algorithm:
- Initialize an empty list to store the result.
- Use a boolean array to keep track of which elements have been used.
- Implement a backtracking function that builds permutations one element at a time.
- When the current permutation reaches the same length as the input, add it to the result.
- Return the list of all permutations.
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
ans = []
used = [False] * len(nums)
def backtracking(path):
if len(path) == len(nums):
ans.append(list(path))
return
for i in range(len(nums)):
if used[i]:
continue
path.append(nums[i])
used[i] = True
backtracking(path)
path.pop()
used[i] = False
backtracking([])
return ans- Time: — There are permutations, and each permutation takes time to construct.
- Space: — The maximum depth of the recursion tree is , and each recursive call uses space.
Last updated on