PracticeNeetCode ↗LeetCode ↗
Given an array nums of distinct integers, return all possible permutations, in any order.
used boolean array instead of slicing the remaining list, to avoid rebuilding a list at every step.path's length equals nums's length.used array of False, length n.backtrack(): if len(path) == len(nums), record a copy of path and return.i in nums: skip it if used[i] is True.used[i] = True, append nums[i] to path, recurse, then undo both (pop path, used[i] = False).backtrack() and return the result.Time: O(n · n!) — Space: O(n) recursion depth
def permute(nums: list[int]) -> list[list[int]]:
result = []
path = []
used = [False] * len(nums)
def backtrack() -> None:
if len(path) == len(nums):
result.append(path[:])
return
for i in range(len(nums)):
if used[i]:
continue
used[i] = True
path.append(nums[i])
backtrack()
path.pop()
used[i] = False
backtrack()
return resultHow the solution above works, piece by piece.
used[i] marks which numbers are already in path.path holds all n numbers, it's a complete permutation: save a copy.The recursion tree for nums = [1, 2, 3]: