Permutations

Medium

Topics
ArrayBacktracking

Given an array nums of distinct integers, return all possible permutations in any order.

Example 1

[1,2,3][1,3,2][2,1,3][2,3,1][3,1,2][3,2,1]
All 6 orderings (3!).
Each chip is one permutation.
Input:  nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

Example 2

[1]
Input:  nums = [1]
Output: [[1]]

Constraints

  • 1 <= nums.length <= 6
  • All integers are unique.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Build a permutation position by position, choosing each unused element in turn. Backtracking with a used-marker explores all n! orderings.

Approach

  1. Track which elements are used.
  2. At each step append an unused element and recurse.
  3. When the path length equals n, record it, then backtrack.

Dry Run

nums = [1, 2, 3]
Unlike subsets there is no `start`: every index is a candidate at every depth, and
`used` is what stops an element appearing twice in one permutation.
  take 1   used [T,F,F]   path [1]
    take 2   used [T,T,F]   path [1,2]
      take 3   used [T,T,T]   path [1,2,3]   complete
    take 3   used [T,F,T]   path [1,3]
      take 2                 path [1,3,2]    complete
  take 2   used [F,T,F]   path [2]
    ... [2,1,3] and [2,3,1]
  take 3   used [F,F,T]   path [3]
    ... [3,1,2] and [3,2,1]
answer 1 2 3 | 1 3 2 | 2 1 3 | 2 3 1 | 3 1 2 | 3 2 1
Watch used go from [T,T,T] back to [T,F,T] between the first and second results.
That reset is the backtracking. Without `used[i] = False` on the way out, each
index is consumed once for the entire search rather than once per branch, and the
output is a single permutation: [[1, 2, 3]].
Both undos are required -- `path.pop()` and the used reset -- and they restore two
different things. Any mutation made on the way down has to be reversed on the way
up, which is the one rule that makes a shared mutable path safe to reuse across
branches.

Complexity

  • Time — O(n * n!): n! permutations, each built in O(n).
  • Space — O(n): recursion depth and used array.

Common Pitfalls

  • Unmark used[i] on the way back out. Without it each index is consumed once for the whole search rather than once per branch, so [1,2,3] yields only 1 2 3 instead of all six orderings.
  • Both undos have to happen -- path.pop() and the used reset. Backtracking is only correct if every mutation made on the way down is reversed on the way up.

Full Solution — all languages

class Solution:
    def permute(self, nums):
        res=[]
        used=[False]*len(nums)
        def dfs(path):
            if len(path)==len(nums): res.append(path[:]); return
            for i in range(len(nums)):
                if used[i]: continue
                used[i]=True; path.append(nums[i]); dfs(path); path.pop(); used[i]=False
        dfs([])
        return res
SensAI
Beta
Tap the mic to stop voice mode