Given an array of distinct integers, return all possible permutations in any order.
Approach: Build permutations by choosing each unused element at each position, then recurse.
Imagine: Arranging People in a Line
- Pick any person for position 1
- Pick any remaining person for position 2
- Continue until all positions filled
- Backtrack to try different arrangements
Example: [1, 2, 3]
Position 1: choose 1 β Position 2: choose 2 β Position 3: choose 3 β [1,2,3]
β backtrack
β Position 2: choose 3 β Position 3: choose 2 β [1,3,2]
β backtrack all the way
Position 1: choose 2 β ...
View v1: dfs | View v2: itertools
def permute(nums: List[int]) -> List[List[int]]:
result = []
def backtrack(path, remaining):
if not remaining:
result.append(path[:])
return
for i in range(len(remaining)):
path.append(remaining[i])
backtrack(path, remaining[:i] + remaining[i+1:])
path.pop()
backtrack([], nums)
return result- Time: O(n! Γ n) - n! permutations, O(n) to copy each
- Space: O(n) - recursion depth
- Permutation = ordering matters - [1,2] β [2,1]
- Track used elements - via remaining list or visited set
- n! results - grows very fast!