Skip to content

13.2   Permutations problem

Generating permutations is a classic application of backtracking. Given a collection, such as an array or a string, the task is to find every possible ordering of its elements.

Table 13-2 gives several input arrays and all their permutations.

Table 13-2   Examples of permutations

Input array All permutations
\([1]\) \([1]\)
\([1, 2]\) \([1, 2], [2, 1]\)
\([1, 2, 3]\) \([1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]\)

13.2.1   Distinct elements

Question

Given an integer array with no duplicate elements, return all possible permutations.

From a backtracking perspective, we can view a permutation as the result of a sequence of choices. For input \([1, 2, 3]\), choosing \(1\), then \(3\), then \(2\) produces \([1, 3, 2]\). Backtracking undoes a choice so that other choices can be tried.

In the code, choices contains all the input elements, and state contains the elements chosen so far. Each element may be chosen only once, so every element in state must be unique.

As shown in Figure 13-5, we can expand the search into a recursion tree, where each node represents the current state. Starting from the root, three rounds of choices lead to a leaf, and each leaf corresponds to one permutation.

Figure 13-5   Recursion tree for permutations

Description of Figure 13-5: Recursive choice tree for permutations of distinct elements

Starting from an empty prefix, choose one unused element from [1, 2, 3] in each round and append it to state, producing 6 permutations after three rounds.

The candidate array is choices = [1, 2, 3], whose three elements are distinct and may each be used only once per permutation. The root node is drawn as three blank slots representing the empty prefix [] before any element is chosen; the blank slots themselves are not element values.

The figure expands all recursive branches simultaneously; in actual backtracking execution, after copying and saving state at a leaf node, the code pops the last element and marks it unselected again before trying sibling branches.

The choice tree has four levels, from the empty prefix at level 0 to the leaf nodes at level 3. The two tables below look up available next choices by prefix and list all six permutations by index.

Available next choices by prefix
Current prefixAvailable elementsNext-level prefixes or leaf result
[]1, 2, 3[1]; [2]; [3]
[1]2, 3[1, 2]; [1, 3]
[2]1, 3[2, 1]; [2, 3]
[3]1, 2[3, 1]; [3, 2]
[1, 2]3[1, 2, 3]
[1, 3]2[1, 3, 2]
[2, 1]3[2, 1, 3]
[2, 3]1[2, 3, 1]
[3, 1]2[3, 1, 2]
[3, 2]1[3, 2, 1]
All six permutations
Result numberComplete permutation
1[1, 2, 3]
2[1, 3, 2]
3[2, 1, 3]
4[2, 3, 1]
5[3, 1, 2]
6[3, 2, 1]

Across the first, second, and third rounds, each node has 3, 2, and 1 available elements respectively, generating 3 × 2 × 1 = 6 leaf nodes corresponding to all 6 permutations of [1, 2, 3].

1.   Pruning repeated selections

To ensure that each element is chosen only once, introduce a Boolean array selected, where selected[i] indicates whether choices[i] has been chosen. Use it for the following pruning steps.

  • After choosing choices[i], set selected[i] to \(\text{True}\) to mark it as selected.
  • When iterating over choices, skip all selected elements, pruning their branches.

As shown in Figure 13-6, if we choose 1 first, 3 second, and 2 third, we must prune the branch for 1 in the second round and the branches for 1 and 3 in the third round.

Figure 13-6   Example of pruning permutations

Description of Figure 13-6: Pruning already chosen elements in permutations

Along the choice path 1 → 3 → 2, use selected to prune element indices already used in the current permutation prefix.

The input is choices = [1, 2, 3] (indices 0, 1, 2), with distinct elements, and each element may be used at most once in a permutation. Here state holds the current permutation prefix, while the Boolean array selected tracks by input index whether each element has already been chosen on the current path.

The selected array only prevents reusing an index along the current recursive path: descending skips marked indices, and backtracking unmarks them on return, so choosing 1 does not disable 1 permanently—it remains available in other permutation branches.

The figure fully expands only the path [] → [1] → [1, 3] → [1, 3, 2]. Pruning marks denote repeated selections that are not entered, such as [1, 1] for choosing element 1 at index 0 again under prefix [1]; ellipses mark valid branches whose continuations are left unexpanded. The table below summarizes choice restrictions and both kinds of branches by prefix.

Choice restrictions along the highlighted path
Current prefixUsed indices (with values)Remaining available valuesValue chosen next in figurePruned and unexpanded branches
[]None1, 2, 31None pruned; [2] and [3] are valid, continuations unexpanded
[1]0 (value 1)2, 33Prune [1, 1]; [1, 2] is valid, continuation unexpanded
[1, 3]0 (value 1), 2 (value 3)22Prune [1, 3, 1] and [1, 3, 3]; no unexpanded branches

The highlighted path ultimately produces permutation [1, 3, 2].

This pruning reduces the search space from \(O(n^n)\) to \(O(n!)\).

2.   Code implementation

With these details established, we can fill in the backtracking template. To keep the code short, we inline the template's helper functions into backtrack():

permutations_i.py
def backtrack(
    state: list[int], choices: list[int], selected: list[bool], res: list[list[int]]
):
    """Backtracking: permutations I"""
    # Record a solution when the state length equals the number of elements
    if len(state) == len(choices):
        res.append(list(state))
        return
    # Iterate over all choices
    for i, choice in enumerate(choices):
        # Prune: do not choose an element more than once
        if not selected[i]:
            # Try: make a choice and update the state
            selected[i] = True
            state.append(choice)
            # Proceed to the next choice
            backtrack(state, choices, selected, res)
            # Backtrack: undo the choice and restore the previous state
            selected[i] = False
            state.pop()

def permutations_i(nums: list[int]) -> list[list[int]]:
    """Permutations I"""
    res = []
    backtrack(state=[], choices=nums, selected=[False] * len(nums), res=res)
    return res
permutations_i.cpp
/* Backtracking: permutations I */
void backtrack(vector<int> &state, const vector<int> &choices, vector<bool> &selected, vector<vector<int>> &res) {
    // Record a solution when the state length equals the number of elements
    if (state.size() == choices.size()) {
        res.push_back(state);
        return;
    }
    // Iterate over all choices
    for (int i = 0; i < choices.size(); i++) {
        int choice = choices[i];
        // Prune: do not choose an element more than once
        if (!selected[i]) {
            // Try: make a choice and update the state
            selected[i] = true;
            state.push_back(choice);
            // Proceed to the next choice
            backtrack(state, choices, selected, res);
            // Backtrack: undo the choice and restore the previous state
            selected[i] = false;
            state.pop_back();
        }
    }
}

/* Permutations I */
vector<vector<int>> permutationsI(vector<int> nums) {
    vector<int> state;
    vector<bool> selected(nums.size(), false);
    vector<vector<int>> res;
    backtrack(state, nums, selected, res);
    return res;
}
permutations_i.java
/* Backtracking: permutations I */
void backtrack(List<Integer> state, int[] choices, boolean[] selected, List<List<Integer>> res) {
    // Record a solution when the state length equals the number of elements
    if (state.size() == choices.length) {
        res.add(new ArrayList<Integer>(state));
        return;
    }
    // Iterate over all choices
    for (int i = 0; i < choices.length; i++) {
        int choice = choices[i];
        // Prune: do not choose an element more than once
        if (!selected[i]) {
            // Try: make a choice and update the state
            selected[i] = true;
            state.add(choice);
            // Proceed to the next choice
            backtrack(state, choices, selected, res);
            // Backtrack: undo the choice and restore the previous state
            selected[i] = false;
            state.remove(state.size() - 1);
        }
    }
}

/* Permutations I */
List<List<Integer>> permutationsI(int[] nums) {
    List<List<Integer>> res = new ArrayList<List<Integer>>();
    backtrack(new ArrayList<Integer>(), nums, new boolean[nums.length], res);
    return res;
}
permutations_i.cs
/* Backtracking: permutations I */
void Backtrack(List<int> state, int[] choices, bool[] selected, List<List<int>> res) {
    // Record a solution when the state length equals the number of elements
    if (state.Count == choices.Length) {
        res.Add(new List<int>(state));
        return;
    }
    // Iterate over all choices
    for (int i = 0; i < choices.Length; i++) {
        int choice = choices[i];
        // Prune: do not choose an element more than once
        if (!selected[i]) {
            // Try: make a choice and update the state
            selected[i] = true;
            state.Add(choice);
            // Proceed to the next choice
            Backtrack(state, choices, selected, res);
            // Backtrack: undo the choice and restore the previous state
            selected[i] = false;
            state.RemoveAt(state.Count - 1);
        }
    }
}

/* Permutations I */
List<List<int>> PermutationsI(int[] nums) {
    List<List<int>> res = [];
    Backtrack([], nums, new bool[nums.Length], res);
    return res;
}
permutations_i.go
/* Backtracking: permutations I */
func backtrackI(state *[]int, choices *[]int, selected *[]bool, res *[][]int) {
    // Record a solution when the state length equals the number of elements
    if len(*state) == len(*choices) {
        newState := append([]int{}, *state...)
        *res = append(*res, newState)
    }
    // Iterate over all choices
    for i := 0; i < len(*choices); i++ {
        choice := (*choices)[i]
        // Prune: do not choose an element more than once
        if !(*selected)[i] {
            // Try: make a choice and update the state
            (*selected)[i] = true
            *state = append(*state, choice)
            // Proceed to the next choice
            backtrackI(state, choices, selected, res)
            // Backtrack: undo the choice and restore the previous state
            (*selected)[i] = false
            *state = (*state)[:len(*state)-1]
        }
    }
}

/* Permutations I */
func permutationsI(nums []int) [][]int {
    res := make([][]int, 0)
    state := make([]int, 0)
    selected := make([]bool, len(nums))
    backtrackI(&state, &nums, &selected, &res)
    return res
}
permutations_i.swift
/* Backtracking: permutations I */
func backtrack(state: inout [Int], choices: [Int], selected: inout [Bool], res: inout [[Int]]) {
    // Record a solution when the state length equals the number of elements
    if state.count == choices.count {
        res.append(state)
        return
    }
    // Iterate over all choices
    for (i, choice) in choices.enumerated() {
        // Prune: do not choose an element more than once
        if !selected[i] {
            // Try: make a choice and update the state
            selected[i] = true
            state.append(choice)
            // Proceed to the next choice
            backtrack(state: &state, choices: choices, selected: &selected, res: &res)
            // Backtrack: undo the choice and restore the previous state
            selected[i] = false
            state.removeLast()
        }
    }
}

/* Permutations I */
func permutationsI(nums: [Int]) -> [[Int]] {
    var state: [Int] = []
    var selected = Array(repeating: false, count: nums.count)
    var res: [[Int]] = []
    backtrack(state: &state, choices: nums, selected: &selected, res: &res)
    return res
}
permutations_i.js
/* Backtracking: permutations I */
function backtrack(state, choices, selected, res) {
    // Record a solution when the state length equals the number of elements
    if (state.length === choices.length) {
        res.push([...state]);
        return;
    }
    // Iterate over all choices
    choices.forEach((choice, i) => {
        // Prune: do not choose an element more than once
        if (!selected[i]) {
            // Try: make a choice and update the state
            selected[i] = true;
            state.push(choice);
            // Proceed to the next choice
            backtrack(state, choices, selected, res);
            // Backtrack: undo the choice and restore the previous state
            selected[i] = false;
            state.pop();
        }
    });
}

/* Permutations I */
function permutationsI(nums) {
    const res = [];
    backtrack([], nums, Array(nums.length).fill(false), res);
    return res;
}
permutations_i.ts
/* Backtracking: permutations I */
function backtrack(
    state: number[],
    choices: number[],
    selected: boolean[],
    res: number[][]
): void {
    // Record a solution when the state length equals the number of elements
    if (state.length === choices.length) {
        res.push([...state]);
        return;
    }
    // Iterate over all choices
    choices.forEach((choice, i) => {
        // Prune: do not choose an element more than once
        if (!selected[i]) {
            // Try: make a choice and update the state
            selected[i] = true;
            state.push(choice);
            // Proceed to the next choice
            backtrack(state, choices, selected, res);
            // Backtrack: undo the choice and restore the previous state
            selected[i] = false;
            state.pop();
        }
    });
}

/* Permutations I */
function permutationsI(nums: number[]): number[][] {
    const res: number[][] = [];
    backtrack([], nums, Array(nums.length).fill(false), res);
    return res;
}
permutations_i.dart
/* Backtracking: permutations I */
void backtrack(
  List<int> state,
  List<int> choices,
  List<bool> selected,
  List<List<int>> res,
) {
  // Record a solution when the state length equals the number of elements
  if (state.length == choices.length) {
    res.add(List.from(state));
    return;
  }
  // Iterate over all choices
  for (int i = 0; i < choices.length; i++) {
    int choice = choices[i];
    // Prune: do not choose an element more than once
    if (!selected[i]) {
      // Try: make a choice and update the state
      selected[i] = true;
      state.add(choice);
      // Proceed to the next choice
      backtrack(state, choices, selected, res);
      // Backtrack: undo the choice and restore the previous state
      selected[i] = false;
      state.removeLast();
    }
  }
}

/* Permutations I */
List<List<int>> permutationsI(List<int> nums) {
  List<List<int>> res = [];
  backtrack([], nums, List.filled(nums.length, false), res);
  return res;
}
permutations_i.rs
/* Backtracking: permutations I */
fn backtrack(mut state: Vec<i32>, choices: &[i32], selected: &mut [bool], res: &mut Vec<Vec<i32>>) {
    // Record a solution when the state length equals the number of elements
    if state.len() == choices.len() {
        res.push(state);
        return;
    }
    // Iterate over all choices
    for i in 0..choices.len() {
        let choice = choices[i];
        // Prune: do not choose an element more than once
        if !selected[i] {
            // Try: make a choice and update the state
            selected[i] = true;
            state.push(choice);
            // Proceed to the next choice
            backtrack(state.clone(), choices, selected, res);
            // Backtrack: undo the choice and restore the previous state
            selected[i] = false;
            state.pop();
        }
    }
}

/* Permutations I */
fn permutations_i(nums: &mut [i32]) -> Vec<Vec<i32>> {
    let mut res = Vec::new(); // Result list (permutations)
    backtrack(Vec::new(), nums, &mut vec![false; nums.len()], &mut res);
    res
}
permutations_i.c
/* Backtracking: permutations I */
void backtrack(int *state, int stateSize, int *choices, int choicesSize, bool *selected, int **res, int *resSize) {
    // Record a solution when the state length equals the number of elements
    if (stateSize == choicesSize) {
        res[*resSize] = (int *)malloc(choicesSize * sizeof(int));
        for (int i = 0; i < choicesSize; i++) {
            res[*resSize][i] = state[i];
        }
        (*resSize)++;
        return;
    }
    // Iterate over all choices
    for (int i = 0; i < choicesSize; i++) {
        int choice = choices[i];
        // Prune: do not choose an element more than once
        if (!selected[i]) {
            // Try: make a choice and update the state
            selected[i] = true;
            state[stateSize] = choice;
            // Proceed to the next choice
            backtrack(state, stateSize + 1, choices, choicesSize, selected, res, resSize);
            // Backtrack: undo the choice and restore the previous state
            selected[i] = false;
        }
    }
}

/* Permutations I */
int **permutationsI(int *nums, int numsSize, int *returnSize) {
    int *state = (int *)malloc(numsSize * sizeof(int));
    bool *selected = (bool *)malloc(numsSize * sizeof(bool));
    for (int i = 0; i < numsSize; i++) {
        selected[i] = false;
    }
    int **res = (int **)malloc(MAX_SIZE * sizeof(int *));
    *returnSize = 0;

    backtrack(state, 0, nums, numsSize, selected, res, returnSize);

    free(state);
    free(selected);

    return res;
}
permutations_i.kt
/* Backtracking: permutations I */
fun backtrack(
    state: MutableList<Int>,
    choices: IntArray,
    selected: BooleanArray,
    res: MutableList<MutableList<Int>?>
) {
    // Record a solution when the state length equals the number of elements
    if (state.size == choices.size) {
        res.add(state.toMutableList())
        return
    }
    // Iterate over all choices
    for (i in choices.indices) {
        val choice = choices[i]
        // Prune: do not choose an element more than once
        if (!selected[i]) {
            // Try: make a choice and update the state
            selected[i] = true
            state.add(choice)
            // Proceed to the next choice
            backtrack(state, choices, selected, res)
            // Backtrack: undo the choice and restore the previous state
            selected[i] = false
            state.removeAt(state.size - 1)
        }
    }
}

/* Permutations I */
fun permutationsI(nums: IntArray): MutableList<MutableList<Int>?> {
    val res = mutableListOf<MutableList<Int>?>()
    backtrack(mutableListOf(), nums, BooleanArray(nums.size), res)
    return res
}
permutations_i.rb
### Backtracking: permutations I ###
def backtrack(state, choices, selected, res)
  # Record a solution when the state length equals the number of elements
  if state.length == choices.length
    res << state.dup
    return
  end

  # Iterate over all choices
  choices.each_with_index do |choice, i|
    # Prune: do not choose an element more than once
    unless selected[i]
      # Try: make a choice and update the state
      selected[i] = true
      state << choice
      # Proceed to the next choice
      backtrack(state, choices, selected, res)
      # Backtrack: undo the choice and restore the previous state
      selected[i] = false
      state.pop
    end
  end
end

### Permutations I ###
def permutations_i(nums)
  res = []
  backtrack([], nums, Array.new(nums.length, false), res)
  res
end
Visualize execution

13.2.2   Duplicate elements

Question

Given an integer array that may contain duplicate elements, return all distinct permutations.

Suppose the input is \([1, 1, 2]\). To distinguish the two occurrences of \(1\), denote the second \(1\) by \(\hat{1}\).

As shown in Figure 13-7, half the permutations generated by the previous method are duplicates.

Figure 13-7   Duplicate permutations

Description of Figure 13-7: Equal elements cause duplicate permutations

Expanding two elements of value 1 as separate candidates produces six paths representing only three distinct numeric permutations.

The input array is choices = [1, 1, 2] at indices 0, 1, and 2. Below, "first 1" and "second 1" distinguish indices 0 and 1; the figure places a hat over the second 1 as an identity marker, though both have numeric value 1. Each index is used at most once along a path, yet preventing index reuse with selected alone still yields numerically identical permutations.

At the top, state has three empty slots. Blue squares denote the first 1, cyan denotes the second 1, and purple denotes 2. Three rounds of choices fill the slots with values from unused indices, expanding into the six leaf nodes in the table below. Entries 3, 4, and 6 have orange borders pointing to "Duplicate permutations to remove". Leaf numbers run from left to right, and the kept-versus-duplicate pairings follow from the orange borders and numeric values.

Six leaf nodes and duplicate pairings
Leaf number (left to right)Permutation distinguishing element identitiesMarking in figure and summary
1[first 1, second 1, 2]No orange border, kept
2[first 1, 2, second 1]No orange border, kept
3[second 1, first 1, 2]Orange border, duplicates entry 1
4[second 1, 2, first 1]Orange border, duplicates entry 2
5[2, first 1, second 1]No orange border, kept
6[2, second 1, first 1]Orange border, duplicates entry 5

Once the element-identity markers are ignored, the six leaf nodes correspond to just three distinct numeric permutations: [1, 1, 2], [1, 2, 1], and [2, 1, 1].

How can we remove these duplicates? A straightforward approach is to use a hash set to deduplicate the results. However, this is inelegant: branches that generate duplicate permutations are unnecessary and should be identified and pruned in advance, improving efficiency.

1.   Pruning equal elements

In Figure 13-8, choosing \(1\) or \(\hat{1}\) in the first round is equivalent: every permutation produced under one choice is duplicated under the other. We should therefore prune \(\hat{1}\).

Similarly, after choosing \(2\) in the first round, choosing either \(1\) or \(\hat{1}\) in the second produces duplicate branches. Prune the second-round choice of \(\hat{1}\) as well.

In essence, within any one round of choices, we want to try only one of the elements with the same value.

Figure 13-8   Pruning duplicate permutations

Description of Figure 13-8: Pruning equal-element branches within a round

Try the repeated value 1 only once per round of choices, pruning duplicate search subtrees in advance.

The input array is choices = [1, 1, 2] at indices 0, 1, and 2. Below, "first 1" and "second 1" distinguish indices 0 and 1; the figure places a hat over the second 1 as an identity marker, though both have numeric value 1.

Two constraints govern indices and values separately: selected tracks indices already used on the current path, while in the code below a per-round deduplication set duplicated records values not skipped by selected and actually tried in the current round. Each recursive call creates its own duplicated set; backtracking restores selected and state without removing values already recorded in that call's set.

The figure explicitly marks only the two same-round prunings that skip the second 1 under the root [] and under prefix [2]. Below, the "One round of choices for each prefix" table completes all six nonterminal prefixes, where the "Skipped due to used index" column follows from the code rules rather than explicit pruning icons in this figure; the "Three unique permutations" table lists each leaf's identity order alongside its numeric values.

One round of choices for each prefix
Current prefixKept candidatesSkipped due to used indexSkipped due to duplicate value in round
[]first 1, 2Nonesecond 1: value 1 already tried in this round
[first 1]second 1, 2first 1: index 0 already on pathNone
[first 1, second 1]2first 1, second 1: corresponding indices already usedNone
[first 1, 2]second 1first 1, 2: corresponding indices already usedNone
[2]first 12: index 2 already on pathsecond 1: value 1 already tried in this round
[2, first 1]second 12, first 1: corresponding indices already usedNone
Three unique permutations
Result numberIdentity notation distinguishing both 1sActual numeric result
1[first 1, second 1, 2][1,1,2]
2[first 1, 2, second 1][1,2,1]
3[2, first 1, second 1][2,1,1]

A single path may still pick both 1s at their two different indices in sequence; within any single round, only one branch is expanded for value 1.

2.   Code implementation

Building on the previous solution, create a hash set duplicated in each round to record the values already tried in that round and prune repeated values:

permutations_ii.py
def backtrack(
    state: list[int], choices: list[int], selected: list[bool], res: list[list[int]]
):
    """Backtracking: permutations II"""
    # Record a solution when the state length equals the number of elements
    if len(state) == len(choices):
        res.append(list(state))
        return
    # Iterate over all choices
    duplicated = set[int]()
    for i, choice in enumerate(choices):
        # Prune: do not reuse an element or choose the same value again at this depth
        if not selected[i] and choice not in duplicated:
            # Try: make a choice and update the state
            duplicated.add(choice)  # Record the chosen value
            selected[i] = True
            state.append(choice)
            # Proceed to the next choice
            backtrack(state, choices, selected, res)
            # Backtrack: undo the choice and restore the previous state
            selected[i] = False
            state.pop()

def permutations_ii(nums: list[int]) -> list[list[int]]:
    """Permutations II"""
    res = []
    backtrack(state=[], choices=nums, selected=[False] * len(nums), res=res)
    return res
permutations_ii.cpp
/* Backtracking: permutations II */
void backtrack(vector<int> &state, const vector<int> &choices, vector<bool> &selected, vector<vector<int>> &res) {
    // Record a solution when the state length equals the number of elements
    if (state.size() == choices.size()) {
        res.push_back(state);
        return;
    }
    // Iterate over all choices
    unordered_set<int> duplicated;
    for (int i = 0; i < choices.size(); i++) {
        int choice = choices[i];
        // Prune: do not reuse an element or choose the same value again at this depth
        if (!selected[i] && duplicated.find(choice) == duplicated.end()) {
            // Try: make a choice and update the state
            duplicated.emplace(choice); // Record the chosen value
            selected[i] = true;
            state.push_back(choice);
            // Proceed to the next choice
            backtrack(state, choices, selected, res);
            // Backtrack: undo the choice and restore the previous state
            selected[i] = false;
            state.pop_back();
        }
    }
}

/* Permutations II */
vector<vector<int>> permutationsII(vector<int> nums) {
    vector<int> state;
    vector<bool> selected(nums.size(), false);
    vector<vector<int>> res;
    backtrack(state, nums, selected, res);
    return res;
}
permutations_ii.java
/* Backtracking: permutations II */
void backtrack(List<Integer> state, int[] choices, boolean[] selected, List<List<Integer>> res) {
    // Record a solution when the state length equals the number of elements
    if (state.size() == choices.length) {
        res.add(new ArrayList<Integer>(state));
        return;
    }
    // Iterate over all choices
    Set<Integer> duplicated = new HashSet<Integer>();
    for (int i = 0; i < choices.length; i++) {
        int choice = choices[i];
        // Prune: do not reuse an element or choose the same value again at this depth
        if (!selected[i] && !duplicated.contains(choice)) {
            // Try: make a choice and update the state
            duplicated.add(choice); // Record the chosen value
            selected[i] = true;
            state.add(choice);
            // Proceed to the next choice
            backtrack(state, choices, selected, res);
            // Backtrack: undo the choice and restore the previous state
            selected[i] = false;
            state.remove(state.size() - 1);
        }
    }
}

/* Permutations II */
List<List<Integer>> permutationsII(int[] nums) {
    List<List<Integer>> res = new ArrayList<List<Integer>>();
    backtrack(new ArrayList<Integer>(), nums, new boolean[nums.length], res);
    return res;
}
permutations_ii.cs
/* Backtracking: permutations II */
void Backtrack(List<int> state, int[] choices, bool[] selected, List<List<int>> res) {
    // Record a solution when the state length equals the number of elements
    if (state.Count == choices.Length) {
        res.Add(new List<int>(state));
        return;
    }
    // Iterate over all choices
    HashSet<int> duplicated = [];
    for (int i = 0; i < choices.Length; i++) {
        int choice = choices[i];
        // Prune: do not reuse an element or choose the same value again at this depth
        if (!selected[i] && !duplicated.Contains(choice)) {
            // Try: make a choice and update the state
            duplicated.Add(choice); // Record the chosen value
            selected[i] = true;
            state.Add(choice);
            // Proceed to the next choice
            Backtrack(state, choices, selected, res);
            // Backtrack: undo the choice and restore the previous state
            selected[i] = false;
            state.RemoveAt(state.Count - 1);
        }
    }
}

/* Permutations II */
List<List<int>> PermutationsII(int[] nums) {
    List<List<int>> res = [];
    Backtrack([], nums, new bool[nums.Length], res);
    return res;
}
permutations_ii.go
/* Backtracking: permutations II */
func backtrackII(state *[]int, choices *[]int, selected *[]bool, res *[][]int) {
    // Record a solution when the state length equals the number of elements
    if len(*state) == len(*choices) {
        newState := append([]int{}, *state...)
        *res = append(*res, newState)
    }
    // Iterate over all choices
    duplicated := make(map[int]struct{}, 0)
    for i := 0; i < len(*choices); i++ {
        choice := (*choices)[i]
        // Prune: do not reuse an element or choose the same value again at this depth
        if _, ok := duplicated[choice]; !ok && !(*selected)[i] {
            // Try: make a choice and update the state
            // Record the chosen value
            duplicated[choice] = struct{}{}
            (*selected)[i] = true
            *state = append(*state, choice)
            // Proceed to the next choice
            backtrackII(state, choices, selected, res)
            // Backtrack: undo the choice and restore the previous state
            (*selected)[i] = false
            *state = (*state)[:len(*state)-1]
        }
    }
}

/* Permutations II */
func permutationsII(nums []int) [][]int {
    res := make([][]int, 0)
    state := make([]int, 0)
    selected := make([]bool, len(nums))
    backtrackII(&state, &nums, &selected, &res)
    return res
}
permutations_ii.swift
/* Backtracking: permutations II */
func backtrack(state: inout [Int], choices: [Int], selected: inout [Bool], res: inout [[Int]]) {
    // Record a solution when the state length equals the number of elements
    if state.count == choices.count {
        res.append(state)
        return
    }
    // Iterate over all choices
    var duplicated: Set<Int> = []
    for (i, choice) in choices.enumerated() {
        // Prune: do not reuse an element or choose the same value again at this depth
        if !selected[i], !duplicated.contains(choice) {
            // Try: make a choice and update the state
            duplicated.insert(choice) // Record the chosen value
            selected[i] = true
            state.append(choice)
            // Proceed to the next choice
            backtrack(state: &state, choices: choices, selected: &selected, res: &res)
            // Backtrack: undo the choice and restore the previous state
            selected[i] = false
            state.removeLast()
        }
    }
}

/* Permutations II */
func permutationsII(nums: [Int]) -> [[Int]] {
    var state: [Int] = []
    var selected = Array(repeating: false, count: nums.count)
    var res: [[Int]] = []
    backtrack(state: &state, choices: nums, selected: &selected, res: &res)
    return res
}
permutations_ii.js
/* Backtracking: permutations II */
function backtrack(state, choices, selected, res) {
    // Record a solution when the state length equals the number of elements
    if (state.length === choices.length) {
        res.push([...state]);
        return;
    }
    // Iterate over all choices
    const duplicated = new Set();
    choices.forEach((choice, i) => {
        // Prune: do not reuse an element or choose the same value again at this depth
        if (!selected[i] && !duplicated.has(choice)) {
            // Try: make a choice and update the state
            duplicated.add(choice); // Record the chosen value
            selected[i] = true;
            state.push(choice);
            // Proceed to the next choice
            backtrack(state, choices, selected, res);
            // Backtrack: undo the choice and restore the previous state
            selected[i] = false;
            state.pop();
        }
    });
}

/* Permutations II */
function permutationsII(nums) {
    const res = [];
    backtrack([], nums, Array(nums.length).fill(false), res);
    return res;
}
permutations_ii.ts
/* Backtracking: permutations II */
function backtrack(
    state: number[],
    choices: number[],
    selected: boolean[],
    res: number[][]
): void {
    // Record a solution when the state length equals the number of elements
    if (state.length === choices.length) {
        res.push([...state]);
        return;
    }
    // Iterate over all choices
    const duplicated = new Set();
    choices.forEach((choice, i) => {
        // Prune: do not reuse an element or choose the same value again at this depth
        if (!selected[i] && !duplicated.has(choice)) {
            // Try: make a choice and update the state
            duplicated.add(choice); // Record the chosen value
            selected[i] = true;
            state.push(choice);
            // Proceed to the next choice
            backtrack(state, choices, selected, res);
            // Backtrack: undo the choice and restore the previous state
            selected[i] = false;
            state.pop();
        }
    });
}

/* Permutations II */
function permutationsII(nums: number[]): number[][] {
    const res: number[][] = [];
    backtrack([], nums, Array(nums.length).fill(false), res);
    return res;
}
permutations_ii.dart
/* Backtracking: permutations II */
void backtrack(
  List<int> state,
  List<int> choices,
  List<bool> selected,
  List<List<int>> res,
) {
  // Record a solution when the state length equals the number of elements
  if (state.length == choices.length) {
    res.add(List.from(state));
    return;
  }
  // Iterate over all choices
  Set<int> duplicated = {};
  for (int i = 0; i < choices.length; i++) {
    int choice = choices[i];
    // Prune: do not reuse an element or choose the same value again at this depth
    if (!selected[i] && !duplicated.contains(choice)) {
      // Try: make a choice and update the state
      duplicated.add(choice); // Record the chosen value
      selected[i] = true;
      state.add(choice);
      // Proceed to the next choice
      backtrack(state, choices, selected, res);
      // Backtrack: undo the choice and restore the previous state
      selected[i] = false;
      state.removeLast();
    }
  }
}

/* Permutations II */
List<List<int>> permutationsII(List<int> nums) {
  List<List<int>> res = [];
  backtrack([], nums, List.filled(nums.length, false), res);
  return res;
}
permutations_ii.rs
/* Backtracking: permutations II */
fn backtrack(mut state: Vec<i32>, choices: &[i32], selected: &mut [bool], res: &mut Vec<Vec<i32>>) {
    // Record a solution when the state length equals the number of elements
    if state.len() == choices.len() {
        res.push(state);
        return;
    }
    // Iterate over all choices
    let mut duplicated = HashSet::<i32>::new();
    for i in 0..choices.len() {
        let choice = choices[i];
        // Prune: do not reuse an element or choose the same value again at this depth
        if !selected[i] && !duplicated.contains(&choice) {
            // Try: make a choice and update the state
            duplicated.insert(choice); // Record the chosen value
            selected[i] = true;
            state.push(choice);
            // Proceed to the next choice
            backtrack(state.clone(), choices, selected, res);
            // Backtrack: undo the choice and restore the previous state
            selected[i] = false;
            state.pop();
        }
    }
}

/* Permutations II */
fn permutations_ii(nums: &mut [i32]) -> Vec<Vec<i32>> {
    let mut res = Vec::new();
    backtrack(Vec::new(), nums, &mut vec![false; nums.len()], &mut res);
    res
}
permutations_ii.c
/* Backtracking: permutations II */
void backtrack(int *state, int stateSize, int *choices, int choicesSize, bool *selected, int **res, int *resSize) {
    // Record a solution when the state length equals the number of elements
    if (stateSize == choicesSize) {
        res[*resSize] = (int *)malloc(choicesSize * sizeof(int));
        for (int i = 0; i < choicesSize; i++) {
            res[*resSize][i] = state[i];
        }
        (*resSize)++;
        return;
    }
    // Iterate over all choices
    bool duplicated[MAX_SIZE] = {false};
    for (int i = 0; i < choicesSize; i++) {
        int choice = choices[i];
        // Prune: do not reuse an element or choose the same value again at this depth
        if (!selected[i] && !duplicated[choice]) {
            // Try: make a choice and update the state
            duplicated[choice] = true; // Record the chosen value
            selected[i] = true;
            state[stateSize] = choice;
            // Proceed to the next choice
            backtrack(state, stateSize + 1, choices, choicesSize, selected, res, resSize);
            // Backtrack: undo the choice and restore the previous state
            selected[i] = false;
        }
    }
}

/* Permutations II */
int **permutationsII(int *nums, int numsSize, int *returnSize) {
    int *state = (int *)malloc(numsSize * sizeof(int));
    bool *selected = (bool *)malloc(numsSize * sizeof(bool));
    for (int i = 0; i < numsSize; i++) {
        selected[i] = false;
    }
    int **res = (int **)malloc(MAX_SIZE * sizeof(int *));
    *returnSize = 0;

    backtrack(state, 0, nums, numsSize, selected, res, returnSize);

    free(state);
    free(selected);

    return res;
}
permutations_ii.kt
/* Backtracking: permutations II */
fun backtrack(
    state: MutableList<Int>,
    choices: IntArray,
    selected: BooleanArray,
    res: MutableList<MutableList<Int>?>
) {
    // Record a solution when the state length equals the number of elements
    if (state.size == choices.size) {
        res.add(state.toMutableList())
        return
    }
    // Iterate over all choices
    val duplicated = HashSet<Int>()
    for (i in choices.indices) {
        val choice = choices[i]
        // Prune: do not reuse an element or choose the same value again at this depth
        if (!selected[i] && !duplicated.contains(choice)) {
            // Try: make a choice and update the state
            duplicated.add(choice) // Record the chosen value
            selected[i] = true
            state.add(choice)
            // Proceed to the next choice
            backtrack(state, choices, selected, res)
            // Backtrack: undo the choice and restore the previous state
            selected[i] = false
            state.removeAt(state.size - 1)
        }
    }
}

/* Permutations II */
fun permutationsII(nums: IntArray): MutableList<MutableList<Int>?> {
    val res = mutableListOf<MutableList<Int>?>()
    backtrack(mutableListOf(), nums, BooleanArray(nums.size), res)
    return res
}
permutations_ii.rb
### Backtracking: permutations II ###
def backtrack(state, choices, selected, res)
  # Record a solution when the state length equals the number of elements
  if state.length == choices.length
    res << state.dup
    return
  end

  # Iterate over all choices
  duplicated = Set.new
  choices.each_with_index do |choice, i|
    # Prune: do not reuse an element or choose the same value again at this depth
    if !selected[i] && !duplicated.include?(choice)
      # Try: make a choice and update the state
      duplicated.add(choice)
      selected[i] = true
      state << choice
      # Proceed to the next choice
      backtrack(state, choices, selected, res)
      # Backtrack: undo the choice and restore the previous state
      selected[i] = false
      state.pop
    end
  end
end

### Permutations II ###
def permutations_ii(nums)
  res = []
  backtrack([], nums, Array.new(nums.length, false), res)
  res
end
Visualize execution

If all elements are distinct, \(n\) elements have \(n!\) permutations, where the exclamation mark denotes factorial. Recording each result requires copying a list of length \(n\), taking \(O(n)\) time. The time complexity is therefore \(O(n!n)\).

The maximum recursion depth is \(n\), requiring \(O(n)\) space for stack frames. The array selected uses \(O(n)\) space. At most \(n\) duplicated sets exist at once, using \(O(n^2)\) space. The space complexity is therefore \(O(n^2)\).

3.   Comparing the two pruning methods

Although both selected and duplicated are used for pruning, they serve different purposes.

  • Pruning repeated selections: There is only one selected array throughout the search. It records which elements are in the current state, preventing the same element from appearing twice in state.
  • Pruning equal elements: Each round of choices (each call to backtrack) has its own duplicated set. It records the values already chosen in that round's for loop, ensuring that equal elements are tried only once in that round.

Figure 13-9 shows the scope of each pruning condition. Each node represents a choice, and the nodes along a path from root to leaf form a permutation.

Figure 13-9   Scope of the two pruning conditions

Description of Figure 13-9: Two permutation pruning rules restricting indices and values

Compare side by side the two pruning conditions: no repeated indices along a path (selected) and no repeated values within a round (duplicated).

The input array is choices = [1, 1, 2] at indices 0, 1, and 2. Below, "first 1" and "second 1" distinguish indices 0 and 1; the figure places a hat over the second 1 as an identity marker, though both have numeric value 1.

Black scissors mark path-index pruning, which forbids reusing an index already on the current path until backtracking makes that index available again. Red scissors mark same-round value pruning: duplicated records only values not skipped by the black scissors and actually chosen during the current call's round, and each recursive call creates a fresh set whose scope differs from selected.

Each square node here represents a single choice, the prefix in the table concatenates the choices along the path from the root to that node, and a complete root-to-leaf path forms a permutation. The first table below separates the black and red scissors shown in the figure into two columns; a cell listing multiple candidates corresponds to multiple pruned branches. The second 1 under the root [] and under prefix [2] is pruned by red scissors, while all branches with already used indices are pruned by black scissors. The second table lists the three unique permutations in order.

One round of choices for each prefix
Current prefixKept candidatesBlack scissors: skipped due to used indexRed scissors: skipped due to duplicate value in round
[]first 1, 2Nonesecond 1: value 1 already tried in this round
[first 1]second 1, 2first 1: index 0 already on pathNone
[first 1, second 1]2first 1, second 1: corresponding indices already usedNone
[first 1, 2]second 1first 1, 2: corresponding indices already usedNone
[2]first 12: index 2 already on pathsecond 1: value 1 already tried in this round
[2, first 1]second 12, first 1: corresponding indices already usedNone
Three unique permutations
Result numberIdentity notation distinguishing both 1sActual numeric result
1[first 1, second 1, 2][1,1,2]
2[first 1, 2, second 1][1,2,1]
3[2, first 1, second 1][2,1,1]

A single path may still pick both 1s at their two different indices in sequence; within any single round, only one branch is expanded for value 1.

Share your insights, questions, or suggestions in the comments