Medium
Permutations
👶 The 5-Year-Old Summary
How many ways can you arrange [1, 2, 3]? List them all! It's like rearranging the order of kids in a line - all possible orderings!
🎮 Interactive Visualizer
Input: [1, 2, 3]
Found:
🧠The Brain Hack
Pick one, then recurse! For each position, try each unused number. Use a "used" array to track what's already in the permutation!
💻 The Clean Solution
def permute(nums):
result = []
used = [False] * len(nums)
def backtrack(current):
# Full permutation found!
if len(current) == len(nums):
result.append(current[:])
return
# Try each unused number
for i in range(len(nums)):
if not used[i]:
used[i] = True
current.append(nums[i])
backtrack(current)
# Backtrack!
current.pop()
used[i] = False
backtrack([])
return result
# [1, 2, 3] → [[1,2,3], [1,3,2], [2,1,3], ...]
Time: O(n! × n)
Space: O(n) recursion + O(n!) output