List every ordering of the input positions while preserving each position’s associated value.
Problem
Input. A list nums of integers.
Output. Return a separate list for every permutation of input positions, with each occurrence used once per result.
Rules. The reference permutes positions, not distinct values, and leaves nums unchanged.
Equal-valued positions remain separate choices, so duplicate value lists may occur.
Returned lists must be independent. Result order is not part of the required contract.
Empty input returns [[]], one empty ordering.
Example. [1, 2] returns [[1, 2], [2, 1]].
For [1, 1], return two independent lists, both [1, 1]; unique-value permutations are a different variant.
Picture
For [1,2,3], flags correspond to input indices 0,1,2:
| Path at call entry | used | Meaning |
|---|---|---|
[] | [F,F,F] | Choose any index |
[1] | [T,F,F] | Index zero is unavailable |
[1,2] | [T,T,F] | Only index two remains |
[1,2,3] | [T,T,T] | Copy one complete ordering |
[1,3] | [T,F,T] | Index one was restored and can follow three |
Emit 123,132,213,231,312,321 in this source’s DFS order. A compact tree label 123 means [1,2,3], not the integer 123.
Unlike subsets, there is no increasing start boundary. Any unused index can follow a later index, allowing [2,1].
At every recursive entry, true flags identify exactly the positions already selected, and path length identifies the next output slot. Pair mark/append with pop/unmark, including after saving a complete path. A returned branch restores its entry state before its sibling runs.
Save a copy only when path length reaches input length. Later pops must not erase an earlier answer. After the outer call returns, path is empty and all flags are false.
Problem trace
Save a copy before unwinding and restoring the live search state
Reference drawing
Problem trace
Save a copy before unwinding and restoring the live search state
Execution trace
Original path and used-index call stack
- active call
- (0, 0)
- input
- nums = [1, 2, 3]
- columns
- path | used indices
Original path and used-index call stack
- active call
- (0, 0)→(1, 0)
- action
- initialize→used[0]=T; append 1
- used by index
- 0:F 1:F 2:F→0:T 1:F 2:F
Original path and used-index call stack
- active call
- (1, 0)→(2, 0)
- action
- used[0]=T; append 1→used[1]=T; append 2
- used by index
- 0:T 1:F 2:F→0:T 1:T 2:F
Original path and used-index call stack
- active call
- (2, 0)→(3, 0)
- action
- used[1]=T; append 2→save 123; pop 3; used[2]=F
- answer
- not shown→[123]
Original path and used-index call stack
- active call
- (3, 0)→(2, 0)
- action
- save 123; pop 3; used[2]=F→pop 2; used[1]=F; append 3
- used by index
- 0:T 1:T 2:T→0:T 1:F 2:T
Original path and used-index call stack
- active call
- (2, 0)→(3, 0)
- action
- pop 2; used[1]=F; append 3→save 132; pop 2; used[1]=F
- answer
- not shown→[123,132]
Original path and used-index call stack
- active call
- (3, 0)→(1, 0)
- action
- save 132; pop 2; used[1]=F→restore branch 1; used[1]=T; append 2
- used by index
- 0:T 1:T 2:T→0:F 1:T 2:F
Original path and used-index call stack
- active call
- (1, 0)→(2, 0)
- action
- restore branch 1; used[1]=T; append 2→used[0]=T; append 1
- used by index
- 0:F 1:T 2:F→0:T 1:T 2:F
Original path and used-index call stack
- active call
- (2, 0)→(3, 0)
- action
- used[0]=T; append 1→save 213; pop 3; used[2]=F
- answer
- not shown→[123,132,213]
Original path and used-index call stack
- active call
- (3, 0)→(2, 0)
- action
- save 213; pop 3; used[2]=F→pop 1; used[0]=F; used[2]=T; append 3
- used by index
- 0:T 1:T 2:T→0:F 1:T 2:T
Original path and used-index call stack
- active call
- (2, 0)→(3, 0)
- action
- pop 1; used[0]=F; used[2]=T; append 3→used[0]=T; append 1; save 231
- answer
- not shown→[123,132,213,231]
Original path and used-index call stack
- active call
- (3, 0)→(1, 0)
- action
- used[0]=T; append 1; save 231→restore branch 2; used[2]=T; append 3
- used by index
- 0:T 1:T 2:T→0:F 1:F 2:T
Original path and used-index call stack
- active call
- (1, 0)→(2, 0)
- action
- restore branch 2; used[2]=T; append 3→used[0]=T; append 1
- used by index
- 0:F 1:F 2:T→0:T 1:F 2:T
Original path and used-index call stack
- active call
- (2, 0)→(3, 0)
- action
- used[0]=T; append 1→save 312; pop 2; used[1]=F
- answer
- not shown→[123,132,213,231,312]
Original path and used-index call stack
- active call
- (3, 0)→(2, 0)
- action
- save 312; pop 2; used[1]=F→pop 1; used[0]=F; used[1]=T; append 2
- used by index
- 0:T 1:T 2:T→0:F 1:T 2:T
Original path and used-index call stack
- active call
- (2, 0)→(3, 0)
- action
- pop 1; used[0]=F; used[1]=T; append 2→save 321; unwind and restore used=[F,F,F]
- after return
- not shown→path=[]; used=[F,F,F]
- Recognize it
- Use this pattern when every ordering is required and each input position may appear exactly once in each complete path.
- Keep true
- At every choose call, used[index] is true exactly when that input position has been selected in the current path. Path length is the next output position, and each returned branch restores both structures to their entry state.
- Reuse it
- Input positions are reusable across sibling branches but forbidden within one path. Mark before recursion and unmark after return. Equal-valued positions remain distinct choices; unique value output requires a separate multiplicity state.
Code
def permutations(nums: list[int]) -> list[list[int]]:
answer: list[list[int]] = []
path: list[int] = []
used = [False] * len(nums)
def choose() -> None:
if len(path) == len(nums):
answer.append(path.copy())
return
for index, num in enumerate(nums):
if not used[index]:
used[index] = True
path.append(num)
choose()
path.pop()
used[index] = False
choose()
return answer
Cost: time and working space.
Working space excludes output: storing lists of length takes slots, including repeated value lists.
Change Length or Value Identity
Start from permutations. Keep reversible state while changing when to emit or which choices are distinct.
-
Return ordered selections of a given length.
New task: Fill only
sizeslots, without reusing an input position.Picture and change: Stop at
size, not input length. Keep every unused index eligible.Code: Complete replacement; an integer size outside
0..len(nums)returns[]:def partial_permutations(nums, size): answer, path = [], [] used = [False] * len(nums) def choose(): if len(path) == size: answer.append(path.copy()) return for index, value in enumerate(nums): if not used[index]: used[index] = True path.append(value) choose() path.pop() used[index] = False if 0 <= size <= len(nums): choose() return answerCheck:
[1,2,3], size two gives six ordered pairs, including[2,1], rather than three unordered subsets. Size zero gives[[]].Use when: Ordering matters but full input length does not. There are position selections. Flags and path use working slots; copied output is additional.
-
Return unique value permutations.
New task: Equal values must not duplicate output, but their full multiplicity must remain available.
Picture and change: Replace position flags with remaining counts. Each distinct value is one branch; decrement before recursion and restore afterward. Counter keys stay fixed while counts change.
Code: Complete replacement for integer values:
from collections import Counter def unique_permutations(nums): counts = Counter(nums) answer, path = [], [] def choose(): if len(path) == len(nums): answer.append(path.copy()) return for value in counts: if counts[value]: counts[value] -= 1 path.append(value) choose() path.pop() counts[value] += 1 choose() return answerCheck:
[1,1,2]gives[1,1,2],[1,2,1],[2,1,1]: three unique orderings, using both ones.Use when: Numeric value identity defines uniqueness. Output count becomes . Working storage is ; copying each result still takes work and slots, and each internal call scans distinct keys.
Rebuild Eligibility
Why would a subset-style start boundary lose valid permutations?
Answer: It forbids earlier indices after later ones. Used flags forbid only positions already selected in this path.