Permutations
List every ordering of distinct numbers by filling one position at a time with an unused number.
The problem
You get an array nums of distinct integers. Return every permutation of it, meaning every way to arrange all of its numbers in a row. The permutations can be listed in any order.
Input nums = [4, 6, 8]
Output [[4, 6, 8], [4, 8, 6], [6, 4, 8], [6, 8, 4], [8, 4, 6], [8, 6, 4]]
3 distinct numbers can be arranged in 3! = 6 ways.
Input nums = [-2, 5]
Output [[-2, 5], [5, -2]]
Either number can go first, and the other one fills the last spot.
Key constraint: nums has at most 6 numbers, and n numbers have n! orderings (720 for six), so listing them all is the job.
How to spot the pattern
- You must list every arrangement, and the order inside an answer matters.
- Each position is a choice among the numbers not used yet, and a choice can be undone.
The idea
Fill the permutation from left to right. Any number not used yet can go in the next position, so try each one in turn: place it, mark it used, fill the remaining positions the same way, then unmark and remove it so the next number gets its turn. When every position is filled, you have one complete permutation.
Brute force: Generate all n^n sequences of n picks and keep the ones that use every number exactly once, which wastes time on the many sequences with repeats.
Step by step
- 1Keep a list
current, ausedflag for each index and a listresult. - 2If
currentholds all n numbers, add a copy of it toresultand return. - 3Otherwise loop over every index
iwhose number is not used yet. - 4Mark
ias used, appendnums[i]and recurse to fill the next position. - 5After the call returns, pop the number and mark
ias unused again.
See the pattern move
The backtracking pattern on a small example. Step through it, or press play.
Code
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
result = []
current = []
used = [False] * len(nums)
def backtrack() -> None:
if len(current) == len(nums):
result.append(current.copy())
return
for i, num in enumerate(nums):
if used[i]:
continue
used[i] = True # choose num for the next position
current.append(num)
backtrack() # fill the remaining positions
current.pop() # undo the choice
used[i] = False
backtrack()
return resultComplexity
Time
O(n * n!)
Space
O(n)
There are n! permutations and each takes O(n) to copy; besides the output, the recursion, current and used hold O(n).
Watch out for
- Saving
currentitself instead of a copy, so every saved permutation keeps changing as you backtrack. - Forgetting to reset
used[i]after the call, so later branches think the number is still taken. - Starting the loop at a
startindex as in Subsets: a permutation can use an earlier number in a later position.
Follow-up questions
What if nums can contain duplicates?
Sort it, and skip nums[i] when it equals nums[i - 1] and nums[i - 1] is not in use, so equal numbers are always placed in one fixed order. That is Permutations II.
Can you do it without the used array?
Yes, by swapping: for position start, swap each number from start onward into it, recurse on start + 1, then swap back. Everything before start is already placed.
In Hinglish
Har position par woh number try karo jo abhi tak use nahi hua. Rakho, aage ki positions bharo, phir hata ke used flag wapas false karo taaki agla number try ho sake.