#46
Medium
Backtracking

Permutations

Return all permutations of the array.

Backtracking

Pattern fit

Unlike subsets, order matters, so each layer chooses one still-unused element and marks it as consumed for deeper recursion.

Key observation

Each recursion level fixes one position in the permutation.

Target complexity

O(n * n!) / O(n)

How to break down the solution cleanly

1

Unlike subsets, order matters, so each layer chooses one still-unused element and marks it as consumed for deeper recursion.

2

Each recursion level fixes one position in the permutation.

3

Model the decision tree explicitly.

4

Choose the next candidate set for the current depth.

Reference implementation

Python
# Generic pattern template
def backtrack(path):
    if complete(path):
        answer.append(path[:])
        return
    for choice in choices(path):
        if not valid(choice, path):
            continue
        path.append(choice)
        backtrack(path)
        path.pop()

Common pitfalls

warning

Forgetting to unmark used elements after recursion.

warning

Appending the same path reference repeatedly.

Common follow-ups

How would you avoid duplicates if values repeat?

Could you write a swap-based version instead?

Continue with related problems

Build repeatable depth inside the Backtracking cluster before moving on.

view_weekBack to the pattern page
LeetCode 46. Permutations Guide | Interview AiBox