Skip to content

13.2   The permutations problem

Generating permutations is a classic application of backtracking. Given a collection such as an array or a string, find all possible orderings of its elements.

The table shows 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.

In backtracking, each permutation is the result of a sequence of choices. For the input array \([1, 2, 3]\), choosing \(1\) first, \(3\) next, and \(2\) last gives the permutation \([1, 3, 2]\). Backtracking undoes a choice so we can try another.

In the code, the candidates choices are all the elements of the input array, and the state state contains the elements chosen so far. Each element may be chosen only once, so all elements in state must be distinct.

We can unfold the search into a recursion tree, as shown below. Each node represents the current state state. Starting at the root, three rounds of choices take us 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 with an empty prefix, append one unused element from [1, 2, 3] to state in each round. Three rounds generate all 6 permutations.

The candidate array choices = [1, 2, 3] contains three distinct elements. Each element can appear only once in a permutation. The root shows three blank slots for the empty prefix []. No values have been filled in, and the blank slots are not themselves elements.

The figure shows every recursive branch at once. In the backtracking code, after saving a copy of state at a leaf, the algorithm pops the last element and marks it as unused again so it can try a sibling branch.

The choice tree has four levels, from the empty prefix at level 0 to the leaves at level 3. The first table gives subsequent choices by prefix, and the second lists all six permutations by number.

Next choices by prefix
Current prefixAvailable elementsNext-level prefixes or leaf results
[]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]

Each node offers 3 choices in the first round, 2 in the second, and 1 in the third. This produces 3 × 2 × 1 = 6 leaves, one for each of the 6 permutations of [1, 2, 3].

1.   Pruning repeated choices

To choose each element only once, use a Boolean array selected. Its entry selected[i] indicates whether choices[i] has already been chosen. We can then prune as follows.

  • After choosing choices[i], set selected[i] to \(\text{True}\) to mark it as used.
  • While iterating through choices, skip any element already chosen, pruning its branch.

Suppose we choose 1 first, 3 second, and 2 third, as shown below. In the second round, prune the branch for 1. In the third round, prune the branches for both 1 and 3.

Figure 13-6   Pruning during permutation generation

Description of Figure 13-6: Pruning previously selected elements when generating permutations

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

The input choices = [1, 2, 3] has distinct elements at indices 0, 1, and 2. Each element can appear only once in a given permutation. The variable state holds the current prefix. The Boolean array selected records, by input index, whether each element has been chosen on the current path.

The restriction in selected applies only to the current recursive path. Skip marked indices on the way down and clear each mark when backtracking from that choice. Choosing 1 does not permanently disable it. Other permutation branches can still use it.

The figure fully expands only the path [] → [1] → [1, 3] → [1, 3, 2]. Pruning marks indicate repeated choices that the search never enters. For example, [1, 1] would select element 1 at index 0 a second time after prefix [1]. Ellipses indicate valid branches whose continuations are omitted. The table groups the choice restrictions, pruned branches, and omitted continuations by prefix.

Choice restrictions along the highlighted path
Current prefixUsed indices (with values)Values still availableNext value chosen in the figurePruned branches and omitted continuations
[]None1, 2, 31None pruned. [2] and [3] are valid, with continuations omitted.
[1]0 (value 1)2, 33Prune [1, 1]. The branch [1, 2] is valid, with its continuation omitted.
[1, 3]0 (value 1), 2 (value 3)22Prune [1, 3, 1] and [1, 3, 3]. No branches are left unexpanded.

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

As the figure shows, pruning reduces the size of the search space from \(O(n^n)\) to \(O(n!)\).

2.   Implementation

We can now fill in the backtracking framework. To keep the code short, we put its operations directly in backtrack() instead of defining each as a separate function:

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 contains all the elements
    if len(state) == len(choices):
        res.append(list(state))
        return
    # Try each choice
    for i, choice in enumerate(choices):
        # Prune: skip elements already in use
        if not selected[i]:
            # Make a choice and update the state
            selected[i] = True
            state.append(choice)
            # Make the next choice
            backtrack(state, choices, selected, res)
            # Backtrack: undo the choice to 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 contains all the elements
    if (state.size() == choices.size()) {
        res.push_back(state);
        return;
    }
    // Try each choice
    for (int i = 0; i < choices.size(); i++) {
        int choice = choices[i];
        // Prune: skip elements already in use
        if (!selected[i]) {
            // Make a choice and update the state
            selected[i] = true;
            state.push_back(choice);
            // Make the next choice
            backtrack(state, choices, selected, res);
            // Backtrack: undo the choice to 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 contains all the elements
    if (state.size() == choices.length) {
        res.add(new ArrayList<Integer>(state));
        return;
    }
    // Try each choice
    for (int i = 0; i < choices.length; i++) {
        int choice = choices[i];
        // Prune: skip elements already in use
        if (!selected[i]) {
            // Make a choice and update the state
            selected[i] = true;
            state.add(choice);
            // Make the next choice
            backtrack(state, choices, selected, res);
            // Backtrack: undo the choice to 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 contains all the elements
    if (state.Count == choices.Length) {
        res.Add(new List<int>(state));
        return;
    }
    // Try each choice
    for (int i = 0; i < choices.Length; i++) {
        int choice = choices[i];
        // Prune: skip elements already in use
        if (!selected[i]) {
            // Make a choice and update the state
            selected[i] = true;
            state.Add(choice);
            // Make the next choice
            Backtrack(state, choices, selected, res);
            // Backtrack: undo the choice to 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 contains all the elements
    if len(*state) == len(*choices) {
        newState := append([]int{}, *state...)
        *res = append(*res, newState)
    }
    // Try each choice
    for i := 0; i < len(*choices); i++ {
        choice := (*choices)[i]
        // Prune: skip elements already in use
        if !(*selected)[i] {
            // Make a choice and update the state
            (*selected)[i] = true
            *state = append(*state, choice)
            // Make the next choice
            backtrackI(state, choices, selected, res)
            // Backtrack: undo the choice to 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 contains all the elements
    if state.count == choices.count {
        res.append(state)
        return
    }
    // Try each choice
    for (i, choice) in choices.enumerated() {
        // Prune: skip elements already in use
        if !selected[i] {
            // Make a choice and update the state
            selected[i] = true
            state.append(choice)
            // Make the next choice
            backtrack(state: &state, choices: choices, selected: &selected, res: &res)
            // Backtrack: undo the choice to 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 contains all the elements
    if (state.length === choices.length) {
        res.push([...state]);
        return;
    }
    // Try each choice
    choices.forEach((choice, i) => {
        // Prune: skip elements already in use
        if (!selected[i]) {
            // Make a choice and update the state
            selected[i] = true;
            state.push(choice);
            // Make the next choice
            backtrack(state, choices, selected, res);
            // Backtrack: undo the choice to 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 contains all the elements
    if (state.length === choices.length) {
        res.push([...state]);
        return;
    }
    // Try each choice
    choices.forEach((choice, i) => {
        // Prune: skip elements already in use
        if (!selected[i]) {
            // Make a choice and update the state
            selected[i] = true;
            state.push(choice);
            // Make the next choice
            backtrack(state, choices, selected, res);
            // Backtrack: undo the choice to 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 contains all the elements
  if (state.length == choices.length) {
    res.add(List.from(state));
    return;
  }
  // Try each choice
  for (int i = 0; i < choices.length; i++) {
    int choice = choices[i];
    // Prune: skip elements already in use
    if (!selected[i]) {
      // Make a choice and update the state
      selected[i] = true;
      state.add(choice);
      // Make the next choice
      backtrack(state, choices, selected, res);
      // Backtrack: undo the choice to 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 contains all the elements
    if state.len() == choices.len() {
        res.push(state);
        return;
    }
    // Try each choice
    for i in 0..choices.len() {
        let choice = choices[i];
        // Prune: skip elements already in use
        if !selected[i] {
            // Make a choice and update the state
            selected[i] = true;
            state.push(choice);
            // Make the next choice
            backtrack(state.clone(), choices, selected, res);
            // Backtrack: undo the choice to 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(); // State (current subset)
    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 contains all the 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;
    }
    // Try each choice
    for (int i = 0; i < choicesSize; i++) {
        int choice = choices[i];
        // Prune: skip elements already in use
        if (!selected[i]) {
            // Make a choice and update the state
            selected[i] = true;
            state[stateSize] = choice;
            // Make the next choice
            backtrack(state, stateSize + 1, choices, choicesSize, selected, res, resSize);
            // Backtrack: undo the choice to 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 contains all the elements
    if (state.size == choices.size) {
        res.add(state.toMutableList())
        return
    }
    // Try each choice
    for (i in choices.indices) {
        val choice = choices[i]
        // Prune: skip elements already in use
        if (!selected[i]) {
            // Make a choice and update the state
            selected[i] = true
            state.add(choice)
            // Make the next choice
            backtrack(state, choices, selected, res)
            // Backtrack: undo the choice to 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 contains all the elements
  if state.length == choices.length
    res << state.dup
    return
  end

  # Try each choice
  choices.each_with_index do |choice, i|
    # Prune: skip elements already in use
    unless selected[i]
      # Make a choice and update the state
      selected[i] = true
      state << choice
      # Make the next choice
      backtrack(state, choices, selected, res)
      # Backtrack: undo the choice to 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   Repeated values

Question

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

Suppose the input is \([1, 1, 2]\). To distinguish the two copies of \(1\), we write the second \(1\) as \(\hat{1}\).

As the figure shows, half the permutations generated by our previous method are duplicates.

Figure 13-7   Duplicate permutations

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

Treating the two elements with value 1 as separate candidates produces six paths but only three distinct value sequences.

The input is choices = [1, 1, 2] at indices 0, 1, and 2. “First 1” and “second 1” distinguish indices 0 and 1. The figure puts a hat on the second 1 to identify it, but both have numerical value 1. An index can appear at most once per path. Using selected to prevent index reuse still allows permutations with identical values.

At the top, state has three empty slots. Blue represents the first 1, teal the second 1, and purple the 2. Each of three rounds fills a slot using an unused index, giving the six leaves in the table. Leaves 3, 4, and 6 have orange borders and point to “Duplicate permutations to remove.” The table numbers leaves from left to right and uses the borders and values to match each duplicate with the permutation to keep.

The six leaves and their duplicate pairs
Leaf number (left to right)Permutation by element identityMarking and interpretation
1[first 1, second 1, 2]No orange border: keep
2[first 1, 2, second 1]No orange border: keep
3[second 1, first 1, 2]Orange border: duplicates item 1
4[second 1, 2, first 1]Orange border: duplicates item 2
5[2, first 1, second 1]No orange border: keep
6[2, second 1, first 1]Orange border: duplicates item 5

Ignoring the identity marks leaves only three distinct value sequences among the six leaves: [1, 1, 2], [1, 2, 1], and [2, 1, 1].

How can we eliminate duplicate permutations? One straightforward approach is to deduplicate the results with a hash set. But branches that generate duplicate permutations do unnecessary work. We can identify and prune them early to improve efficiency.

1.   Pruning equal values

In Figure 13-8, choosing \(1\) or \(\hat{1}\) in the first round produces exactly the same permutations. We can therefore prune \(\hat{1}\).

Similarly, after choosing \(2\) in the first round, choosing \(1\) or \(\hat{1}\) in the second round produces duplicate branches, so prune \(\hat{1}\) in that round as well.

Our goal is to try only one of several equal elements in any given round.

Figure 13-8   Pruning duplicate permutations

Description of Figure 13-8: Pruning equal choices in the same round

Try the value 1 only once in a round to prune duplicate subtrees before exploring them.

The input is choices = [1, 1, 2] at indices 0, 1, and 2. “First 1” and “second 1” distinguish indices 0 and 1. The figure marks the second 1 with a hat to identify it. Both have numerical value 1.

Two constraints track indices and values separately. The array selected tracks indices used on the current path. The set duplicated in the code below tracks values actually chosen in the current round after the selected check. Each recursive call creates its own duplicated. Backtracking restores selected and state but retains values already tried in the current call’s set.

The figure marks only two same-round pruning decisions: skipping the second 1 at root [] and after prefix [2]. The table of choices by prefix gives the decisions at all six nonterminal prefixes. Its column for used indices follows from the code and does not correspond to pruning marks in the figure. The table of three distinct permutations gives both the element identities and the resulting values at each leaf.

One round of choices for each prefix
Current prefixCandidates keptSkipped because the index is in useSkipped because the value repeats in this round
[]First 1, 2NoneSecond 1: value 1 already tried this round
[first 1]Second 1, 2First 1: index 0 is already on the pathNone
[first 1, second 1]2First 1 and second 1: both indices are in useNone
[first 1, 2]Second 1First 1 and 2: both indices are in useNone
[2]First 12: index 2 is already on the pathSecond 1: value 1 already tried this round
[2, first 1]Second 12 and first 1: both indices are in useNone
Three distinct permutations
Result numberNotation distinguishing the two 1sResulting values
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 path can choose both 1s in succession because they have distinct indices. Within any one round, only one branch is expanded for the value 1.

2.   Implementation

Extend the previous implementation with a fresh hash set duplicated in each round. Use it to track the values already tried in that round and prune duplicates:

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 contains all the elements
    if len(state) == len(choices):
        res.append(list(state))
        return
    # Try each choice
    duplicated = set[int]()
    for i, choice in enumerate(choices):
        # Skip elements already in use and values already tried at this level
        if not selected[i] and choice not in duplicated:
            # Make a choice and update the state
            duplicated.add(choice)  # Track values already tried
            selected[i] = True
            state.append(choice)
            # Make the next choice
            backtrack(state, choices, selected, res)
            # Backtrack: undo the choice to 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 contains all the elements
    if (state.size() == choices.size()) {
        res.push_back(state);
        return;
    }
    // Try each choice
    unordered_set<int> duplicated;
    for (int i = 0; i < choices.size(); i++) {
        int choice = choices[i];
        // Skip elements already in use and values already tried at this level
        if (!selected[i] && duplicated.find(choice) == duplicated.end()) {
            // Make a choice and update the state
            duplicated.emplace(choice); // Track values already tried
            selected[i] = true;
            state.push_back(choice);
            // Make the next choice
            backtrack(state, choices, selected, res);
            // Backtrack: undo the choice to 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 contains all the elements
    if (state.size() == choices.length) {
        res.add(new ArrayList<Integer>(state));
        return;
    }
    // Try each choice
    Set<Integer> duplicated = new HashSet<Integer>();
    for (int i = 0; i < choices.length; i++) {
        int choice = choices[i];
        // Skip elements already in use and values already tried at this level
        if (!selected[i] && !duplicated.contains(choice)) {
            // Make a choice and update the state
            duplicated.add(choice); // Track values already tried
            selected[i] = true;
            state.add(choice);
            // Make the next choice
            backtrack(state, choices, selected, res);
            // Backtrack: undo the choice to 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 contains all the elements
    if (state.Count == choices.Length) {
        res.Add(new List<int>(state));
        return;
    }
    // Try each choice
    HashSet<int> duplicated = [];
    for (int i = 0; i < choices.Length; i++) {
        int choice = choices[i];
        // Skip elements already in use and values already tried at this level
        if (!selected[i] && !duplicated.Contains(choice)) {
            // Make a choice and update the state
            duplicated.Add(choice); // Track values already tried
            selected[i] = true;
            state.Add(choice);
            // Make the next choice
            Backtrack(state, choices, selected, res);
            // Backtrack: undo the choice to 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 contains all the elements
    if len(*state) == len(*choices) {
        newState := append([]int{}, *state...)
        *res = append(*res, newState)
    }
    // Try each choice
    duplicated := make(map[int]struct{}, 0)
    for i := 0; i < len(*choices); i++ {
        choice := (*choices)[i]
        // Skip elements already in use and values already tried at this level
        if _, ok := duplicated[choice]; !ok && !(*selected)[i] {
            // Make a choice and update the state
            // Track values already tried
            duplicated[choice] = struct{}{}
            (*selected)[i] = true
            *state = append(*state, choice)
            // Make the next choice
            backtrackII(state, choices, selected, res)
            // Backtrack: undo the choice to 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 contains all the elements
    if state.count == choices.count {
        res.append(state)
        return
    }
    // Try each choice
    var duplicated: Set<Int> = []
    for (i, choice) in choices.enumerated() {
        // Skip elements already in use and values already tried at this level
        if !selected[i], !duplicated.contains(choice) {
            // Make a choice and update the state
            duplicated.insert(choice) // Track values already tried
            selected[i] = true
            state.append(choice)
            // Make the next choice
            backtrack(state: &state, choices: choices, selected: &selected, res: &res)
            // Backtrack: undo the choice to 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 contains all the elements
    if (state.length === choices.length) {
        res.push([...state]);
        return;
    }
    // Try each choice
    const duplicated = new Set();
    choices.forEach((choice, i) => {
        // Skip elements already in use and values already tried at this level
        if (!selected[i] && !duplicated.has(choice)) {
            // Make a choice and update the state
            duplicated.add(choice); // Track values already tried
            selected[i] = true;
            state.push(choice);
            // Make the next choice
            backtrack(state, choices, selected, res);
            // Backtrack: undo the choice to 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 contains all the elements
    if (state.length === choices.length) {
        res.push([...state]);
        return;
    }
    // Try each choice
    const duplicated = new Set();
    choices.forEach((choice, i) => {
        // Skip elements already in use and values already tried at this level
        if (!selected[i] && !duplicated.has(choice)) {
            // Make a choice and update the state
            duplicated.add(choice); // Track values already tried
            selected[i] = true;
            state.push(choice);
            // Make the next choice
            backtrack(state, choices, selected, res);
            // Backtrack: undo the choice to 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 contains all the elements
  if (state.length == choices.length) {
    res.add(List.from(state));
    return;
  }
  // Try each choice
  Set<int> duplicated = {};
  for (int i = 0; i < choices.length; i++) {
    int choice = choices[i];
    // Skip elements already in use and values already tried at this level
    if (!selected[i] && !duplicated.contains(choice)) {
      // Make a choice and update the state
      duplicated.add(choice); // Track values already tried
      selected[i] = true;
      state.add(choice);
      // Make the next choice
      backtrack(state, choices, selected, res);
      // Backtrack: undo the choice to 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 contains all the elements
    if state.len() == choices.len() {
        res.push(state);
        return;
    }
    // Try each choice
    let mut duplicated = HashSet::<i32>::new();
    for i in 0..choices.len() {
        let choice = choices[i];
        // Skip elements already in use and values already tried at this level
        if !selected[i] && !duplicated.contains(&choice) {
            // Make a choice and update the state
            duplicated.insert(choice); // Track values already tried
            selected[i] = true;
            state.push(choice);
            // Make the next choice
            backtrack(state.clone(), choices, selected, res);
            // Backtrack: undo the choice to 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 contains all the 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;
    }
    // Try each choice
    bool duplicated[MAX_SIZE] = {false};
    for (int i = 0; i < choicesSize; i++) {
        int choice = choices[i];
        // Skip elements already in use and values already tried at this level
        if (!selected[i] && !duplicated[choice]) {
            // Make a choice and update the state
            duplicated[choice] = true; // Track values already tried
            selected[i] = true;
            state[stateSize] = choice;
            // Make the next choice
            backtrack(state, stateSize + 1, choices, choicesSize, selected, res, resSize);
            // Backtrack: undo the choice to 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 contains all the elements
    if (state.size == choices.size) {
        res.add(state.toMutableList())
        return
    }
    // Try each choice
    val duplicated = HashSet<Int>()
    for (i in choices.indices) {
        val choice = choices[i]
        // Skip elements already in use and values already tried at this level
        if (!selected[i] && !duplicated.contains(choice)) {
            // Make a choice and update the state
            duplicated.add(choice) // Track values already tried
            selected[i] = true
            state.add(choice)
            // Make the next choice
            backtrack(state, choices, selected, res)
            // Backtrack: undo the choice to 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 contains all the elements
  if state.length == choices.length
    res << state.dup
    return
  end

  # Try each choice
  duplicated = Set.new
  choices.each_with_index do |choice, i|
    # Skip elements already in use and values already tried at this level
    if !selected[i] && !duplicated.include?(choice)
      # Make a choice and update the state
      duplicated.add(choice)
      selected[i] = true
      state << choice
      # Make the next choice
      backtrack(state, choices, selected, res)
      # Backtrack: undo the choice to 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

Assuming distinct values, \(n\) elements have \(n!\) permutations (factorial). Recording each result requires copying a list of length \(n\), which takes \(O(n)\) time. The time complexity is therefore \(O(n!n)\).

The maximum recursion depth is \(n\), so stack frames take \(O(n)\) space. The array selected takes \(O(n)\) space. At most \(n\) instances of duplicated coexist, using \(O(n^2)\) space. The space complexity is therefore \(O(n^2)\).

3.   Comparing the two pruning rules

Both selected and duplicated help prune the search, but they serve different purposes.

  • Pruning repeated choices: The entire search shares one selected. It tracks the elements in the current state and prevents the same element from appearing twice in state.
  • Pruning equal values: Each round (each call to backtrack) has its own duplicated. It tracks values already tried in that round’s for loop, so equal elements are tried only once.

The figure shows where each pruning rule applies. Each node represents a choice, and the choices along a path from the root to a leaf form a permutation.

Figure 13-9   Where the two pruning rules apply

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

Compare pruning repeated indices on a path (selected) with pruning repeated values in a round (duplicated).

The input is choices = [1, 1, 2] at indices 0, 1, and 2. “First 1” and “second 1” distinguish indices 0 and 1. The figure marks the second 1 with a hat to identify it. Both have numerical value 1.

Black scissors prune indices already used on the current path. Backtracking makes those indices available again. Red scissors prune repeated values within one round. Each call creates its own duplicated set. It records only values actually chosen in that call after the black-scissors check, so its scope differs from that of selected.

Each square node represents a choice. Reading the choices from the root to a node gives the prefix shown in the table. A complete root-to-leaf path forms a permutation. The first table has separate columns for black and red scissors. Multiple candidates in a cell indicate multiple pruned branches. Red scissors prune the second 1 at root [] and at prefix [2]. Black scissors prune the other branches that reuse indices. The second table lists the three distinct permutations by number.

One round of choices for each prefix
Current prefixCandidates keptBlack scissors: skip an index already in useRed scissors: skip a value already tried this round
[]First 1, 2NoneSecond 1: value 1 already tried this round
[first 1]Second 1, 2First 1: index 0 is already on the pathNone
[first 1, second 1]2First 1 and second 1: both indices are in useNone
[first 1, 2]Second 1First 1 and 2: both indices are in useNone
[2]First 12: index 2 is already on the pathSecond 1: value 1 already tried this round
[2, first 1]Second 12 and first 1: both indices are in useNone
Three distinct permutations
Result numberNotation distinguishing the two 1sResulting values
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 path can choose both 1s in succession because they have distinct indices. Within any one round, only one branch is expanded for the value 1.

Share your thoughts, questions, or suggestions in the comments.