13.2 全排列问题¶
全排列问题是回溯算法的一个典型应用。它的定义是在给定一个集合(如一个数组或字符串)的情况下,找出其中元素的所有可能的排列。
表 13-2 列举了几个示例数据,包括输入数组和对应的所有排列。
表 13-2 全排列示例
| 输入数组 | 所有排列 |
|---|---|
| \([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 无相等元素的情况¶
Question
输入一个整数数组,其中不包含重复元素,返回所有可能的排列。
从回溯算法的角度看,我们可以把生成排列的过程想象成一系列选择的结果。假设输入数组为 \([1, 2, 3]\) ,如果我们先选择 \(1\) ,再选择 \(3\) ,最后选择 \(2\) ,则获得排列 \([1, 3, 2]\) 。回退表示撤销一个选择,之后继续尝试其他选择。
从回溯代码的角度看,候选集合 choices 是输入数组中的所有元素,状态 state 是直至目前已被选择的元素。请注意,每个元素只允许被选择一次,因此 state 中的所有元素都应该是唯一的。
如图 13-5 所示,我们可以将搜索过程展开成一棵递归树,树中的每个节点代表当前状态 state 。从根节点开始,经过三轮选择后到达叶节点,每个叶节点都对应一个排列。
图 13-5 全排列的递归树
图解 13-5:无相等元素全排列的递归选择树
从空前缀出发,每轮从 [1, 2, 3] 中选一个未用元素追加到 state,三轮生成 6 个全排列。
输入候选数组 choices = [1, 2, 3],三个元素互不相同,且同一排列中每个元素只能使用一次。根节点画为三个空白槽位,表示尚未填入任何元素的空前缀 [],空白槽位本身不是元素值。
图将所有递归分支同时展开,实际回溯代码在叶节点复制保存 state 后,会弹出末尾元素并恢复该元素的未选状态以尝试兄弟分支。
选择树共四层,从第 0 层空前缀到第 3 层叶节点。下方两表分别按前缀查后续选择、按序号查全部六个排列。
| 当前前缀 | 可选元素 | 下一层前缀或叶结果 |
|---|---|---|
| [] | 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] |
| 结果序号 | 完整排列 |
|---|---|
| 1 | [1, 2, 3] |
| 2 | [1, 3, 2] |
| 3 | [2, 1, 3] |
| 4 | [2, 3, 1] |
| 5 | [3, 1, 2] |
| 6 | [3, 2, 1] |
第一、二、三轮每个节点的可选元素个数依次为 3、2、1,共生成 3 × 2 × 1 = 6 个叶节点,对应 [1, 2, 3] 的全部 6 个全排列。
1. 重复选择剪枝¶
为了实现每个元素只被选择一次,我们考虑引入一个布尔型数组 selected ,其中 selected[i] 表示 choices[i] 是否已被选择,并基于它实现以下剪枝操作。
- 在做出选择
choices[i]后,我们就将selected[i]赋值为 \(\text{True}\) ,代表它已被选择。 - 遍历选择列表
choices时,跳过所有已被选择的节点,即剪枝。
如图 13-6 所示,假设我们第一轮选择 1 ,第二轮选择 3 ,第三轮选择 2 ,则需要在第二轮剪掉元素 1 的分支,在第三轮剪掉元素 1 和元素 3 的分支。
图 13-6 全排列剪枝示例
图解 13-6:全排列中剪掉已选元素
沿 1 → 3 → 2 的选择路径,用 selected 剪去当前排列前缀中已使用过的元素索引。
输入为 choices = [1, 2, 3](索引 0、1、2),无相等元素,每个元素在同一排列中只能使用一次。state 保存当前排列前缀,布尔数组 selected 按输入索引记录该元素在当前路径中是否已被选用。
selected 仅限制当前递归路径内不重复选用同一索引:向下递归时跳过已标记索引,回溯返回时则会撤销该标记,因此选过 1 不会永久禁用 1,它在其他排列分支中仍可再次使用。
图只完整展开 [] → [1] → [1, 3] → [1, 3, 2] 这一条路径。剪枝标记表示不实际进入的重复选择,例如 [1, 1] 表示在前缀 [1] 下再选一次索引 0 的元素 1;省略号表示合法分支的后续未画出。下表按前缀合并列出选择限制与这两类分支。
| 当前前缀 | 已用索引(对应值) | 仍可选择的值 | 图中继续选择的值 | 剪除与收起的分支 |
|---|---|---|---|---|
| [] | 无 | 1、2、3 | 1 | 无剪除;[2]、[3] 合法,后续未展开 |
| [1] | 0(值 1) | 2、3 | 3 | 剪除 [1, 1];[1, 2] 合法,后续未展开 |
| [1, 3] | 0(值 1)、2(值 3) | 2 | 2 | 剪除 [1, 3, 1]、[1, 3, 3];无未展开分支 |
突出路径最终生成排列 [1, 3, 2]。
观察图 13-6 发现,该剪枝操作将搜索空间大小从 \(O(n^n)\) 减小至 \(O(n!)\) 。
2. 代码实现¶
想清楚以上信息之后,我们就可以在框架代码中做“完形填空”了。为了缩短整体代码,我们不单独实现框架代码中的各个函数,而是将它们展开在 backtrack() 函数中:
def backtrack(
state: list[int], choices: list[int], selected: list[bool], res: list[list[int]]
):
"""回溯算法:全排列 I"""
# 当状态长度等于元素数量时,记录解
if len(state) == len(choices):
res.append(list(state))
return
# 遍历所有选择
for i, choice in enumerate(choices):
# 剪枝:不允许重复选择元素
if not selected[i]:
# 尝试:做出选择,更新状态
selected[i] = True
state.append(choice)
# 进行下一轮选择
backtrack(state, choices, selected, res)
# 回退:撤销选择,恢复到之前的状态
selected[i] = False
state.pop()
def permutations_i(nums: list[int]) -> list[list[int]]:
"""全排列 I"""
res = []
backtrack(state=[], choices=nums, selected=[False] * len(nums), res=res)
return res
/* 回溯算法:全排列 I */
void backtrack(vector<int> &state, const vector<int> &choices, vector<bool> &selected, vector<vector<int>> &res) {
// 当状态长度等于元素数量时,记录解
if (state.size() == choices.size()) {
res.push_back(state);
return;
}
// 遍历所有选择
for (int i = 0; i < choices.size(); i++) {
int choice = choices[i];
// 剪枝:不允许重复选择元素
if (!selected[i]) {
// 尝试:做出选择,更新状态
selected[i] = true;
state.push_back(choice);
// 进行下一轮选择
backtrack(state, choices, selected, res);
// 回退:撤销选择,恢复到之前的状态
selected[i] = false;
state.pop_back();
}
}
}
/* 全排列 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;
}
/* 回溯算法:全排列 I */
void backtrack(List<Integer> state, int[] choices, boolean[] selected, List<List<Integer>> res) {
// 当状态长度等于元素数量时,记录解
if (state.size() == choices.length) {
res.add(new ArrayList<Integer>(state));
return;
}
// 遍历所有选择
for (int i = 0; i < choices.length; i++) {
int choice = choices[i];
// 剪枝:不允许重复选择元素
if (!selected[i]) {
// 尝试:做出选择,更新状态
selected[i] = true;
state.add(choice);
// 进行下一轮选择
backtrack(state, choices, selected, res);
// 回退:撤销选择,恢复到之前的状态
selected[i] = false;
state.remove(state.size() - 1);
}
}
}
/* 全排列 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;
}
/* 回溯算法:全排列 I */
void Backtrack(List<int> state, int[] choices, bool[] selected, List<List<int>> res) {
// 当状态长度等于元素数量时,记录解
if (state.Count == choices.Length) {
res.Add(new List<int>(state));
return;
}
// 遍历所有选择
for (int i = 0; i < choices.Length; i++) {
int choice = choices[i];
// 剪枝:不允许重复选择元素
if (!selected[i]) {
// 尝试:做出选择,更新状态
selected[i] = true;
state.Add(choice);
// 进行下一轮选择
Backtrack(state, choices, selected, res);
// 回退:撤销选择,恢复到之前的状态
selected[i] = false;
state.RemoveAt(state.Count - 1);
}
}
}
/* 全排列 I */
List<List<int>> PermutationsI(int[] nums) {
List<List<int>> res = [];
Backtrack([], nums, new bool[nums.Length], res);
return res;
}
/* 回溯算法:全排列 I */
func backtrackI(state *[]int, choices *[]int, selected *[]bool, res *[][]int) {
// 当状态长度等于元素数量时,记录解
if len(*state) == len(*choices) {
newState := append([]int{}, *state...)
*res = append(*res, newState)
}
// 遍历所有选择
for i := 0; i < len(*choices); i++ {
choice := (*choices)[i]
// 剪枝:不允许重复选择元素
if !(*selected)[i] {
// 尝试:做出选择,更新状态
(*selected)[i] = true
*state = append(*state, choice)
// 进行下一轮选择
backtrackI(state, choices, selected, res)
// 回退:撤销选择,恢复到之前的状态
(*selected)[i] = false
*state = (*state)[:len(*state)-1]
}
}
}
/* 全排列 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
}
/* 回溯算法:全排列 I */
func backtrack(state: inout [Int], choices: [Int], selected: inout [Bool], res: inout [[Int]]) {
// 当状态长度等于元素数量时,记录解
if state.count == choices.count {
res.append(state)
return
}
// 遍历所有选择
for (i, choice) in choices.enumerated() {
// 剪枝:不允许重复选择元素
if !selected[i] {
// 尝试:做出选择,更新状态
selected[i] = true
state.append(choice)
// 进行下一轮选择
backtrack(state: &state, choices: choices, selected: &selected, res: &res)
// 回退:撤销选择,恢复到之前的状态
selected[i] = false
state.removeLast()
}
}
}
/* 全排列 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
}
/* 回溯算法:全排列 I */
function backtrack(state, choices, selected, res) {
// 当状态长度等于元素数量时,记录解
if (state.length === choices.length) {
res.push([...state]);
return;
}
// 遍历所有选择
choices.forEach((choice, i) => {
// 剪枝:不允许重复选择元素
if (!selected[i]) {
// 尝试:做出选择,更新状态
selected[i] = true;
state.push(choice);
// 进行下一轮选择
backtrack(state, choices, selected, res);
// 回退:撤销选择,恢复到之前的状态
selected[i] = false;
state.pop();
}
});
}
/* 全排列 I */
function permutationsI(nums) {
const res = [];
backtrack([], nums, Array(nums.length).fill(false), res);
return res;
}
/* 回溯算法:全排列 I */
function backtrack(
state: number[],
choices: number[],
selected: boolean[],
res: number[][]
): void {
// 当状态长度等于元素数量时,记录解
if (state.length === choices.length) {
res.push([...state]);
return;
}
// 遍历所有选择
choices.forEach((choice, i) => {
// 剪枝:不允许重复选择元素
if (!selected[i]) {
// 尝试:做出选择,更新状态
selected[i] = true;
state.push(choice);
// 进行下一轮选择
backtrack(state, choices, selected, res);
// 回退:撤销选择,恢复到之前的状态
selected[i] = false;
state.pop();
}
});
}
/* 全排列 I */
function permutationsI(nums: number[]): number[][] {
const res: number[][] = [];
backtrack([], nums, Array(nums.length).fill(false), res);
return res;
}
/* 回溯算法:全排列 I */
void backtrack(
List<int> state,
List<int> choices,
List<bool> selected,
List<List<int>> res,
) {
// 当状态长度等于元素数量时,记录解
if (state.length == choices.length) {
res.add(List.from(state));
return;
}
// 遍历所有选择
for (int i = 0; i < choices.length; i++) {
int choice = choices[i];
// 剪枝:不允许重复选择元素
if (!selected[i]) {
// 尝试:做出选择,更新状态
selected[i] = true;
state.add(choice);
// 进行下一轮选择
backtrack(state, choices, selected, res);
// 回退:撤销选择,恢复到之前的状态
selected[i] = false;
state.removeLast();
}
}
}
/* 全排列 I */
List<List<int>> permutationsI(List<int> nums) {
List<List<int>> res = [];
backtrack([], nums, List.filled(nums.length, false), res);
return res;
}
/* 回溯算法:全排列 I */
fn backtrack(mut state: Vec<i32>, choices: &[i32], selected: &mut [bool], res: &mut Vec<Vec<i32>>) {
// 当状态长度等于元素数量时,记录解
if state.len() == choices.len() {
res.push(state);
return;
}
// 遍历所有选择
for i in 0..choices.len() {
let choice = choices[i];
// 剪枝:不允许重复选择元素
if !selected[i] {
// 尝试:做出选择,更新状态
selected[i] = true;
state.push(choice);
// 进行下一轮选择
backtrack(state.clone(), choices, selected, res);
// 回退:撤销选择,恢复到之前的状态
selected[i] = false;
state.pop();
}
}
}
/* 全排列 I */
fn permutations_i(nums: &mut [i32]) -> Vec<Vec<i32>> {
let mut res = Vec::new(); // 状态(子集)
backtrack(Vec::new(), nums, &mut vec![false; nums.len()], &mut res);
res
}
/* 回溯算法:全排列 I */
void backtrack(int *state, int stateSize, int *choices, int choicesSize, bool *selected, int **res, int *resSize) {
// 当状态长度等于元素数量时,记录解
if (stateSize == choicesSize) {
res[*resSize] = (int *)malloc(choicesSize * sizeof(int));
for (int i = 0; i < choicesSize; i++) {
res[*resSize][i] = state[i];
}
(*resSize)++;
return;
}
// 遍历所有选择
for (int i = 0; i < choicesSize; i++) {
int choice = choices[i];
// 剪枝:不允许重复选择元素
if (!selected[i]) {
// 尝试:做出选择,更新状态
selected[i] = true;
state[stateSize] = choice;
// 进行下一轮选择
backtrack(state, stateSize + 1, choices, choicesSize, selected, res, resSize);
// 回退:撤销选择,恢复到之前的状态
selected[i] = false;
}
}
}
/* 全排列 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;
}
/* 回溯算法:全排列 I */
fun backtrack(
state: MutableList<Int>,
choices: IntArray,
selected: BooleanArray,
res: MutableList<MutableList<Int>?>
) {
// 当状态长度等于元素数量时,记录解
if (state.size == choices.size) {
res.add(state.toMutableList())
return
}
// 遍历所有选择
for (i in choices.indices) {
val choice = choices[i]
// 剪枝:不允许重复选择元素
if (!selected[i]) {
// 尝试:做出选择,更新状态
selected[i] = true
state.add(choice)
// 进行下一轮选择
backtrack(state, choices, selected, res)
// 回退:撤销选择,恢复到之前的状态
selected[i] = false
state.removeAt(state.size - 1)
}
}
}
/* 全排列 I */
fun permutationsI(nums: IntArray): MutableList<MutableList<Int>?> {
val res = mutableListOf<MutableList<Int>?>()
backtrack(mutableListOf(), nums, BooleanArray(nums.size), res)
return res
}
### 回溯算法:全排列 I ###
def backtrack(state, choices, selected, res)
# 当状态长度等于元素数量时,记录解
if state.length == choices.length
res << state.dup
return
end
# 遍历所有选择
choices.each_with_index do |choice, i|
# 剪枝:不允许重复选择元素
unless selected[i]
# 尝试:做出选择,更新状态
selected[i] = true
state << choice
# 进行下一轮选择
backtrack(state, choices, selected, res)
# 回退:撤销选择,恢复到之前的状态
selected[i] = false
state.pop
end
end
end
### 全排列 I ###
def permutations_i(nums)
res = []
backtrack([], nums, Array.new(nums.length, false), res)
res
end
可视化运行
13.2.2 考虑相等元素的情况¶
Question
输入一个整数数组,数组中可能包含重复元素,返回所有不重复的排列。
假设输入数组为 \([1, 1, 2]\) 。为了方便区分两个重复元素 \(1\) ,我们将第二个 \(1\) 记为 \(\hat{1}\) 。
如图 13-7 所示,上述方法生成的排列有一半是重复的。
图 13-7 重复排列
图解 13-7:相等元素使全排列重复
把两个值为 1 的元素当作不同候选展开,会产生六条路径但只有三种不同的数值排列。
输入数组为 choices = [1, 1, 2],索引依次为 0、1、2。下文用“第一个 1”和“第二个 1”区分索引 0 与 1;原图在第二个 1 上加帽作身份标记,两者的实际数值都为 1。每个索引在一条排列路径中最多用一次,但仅靠 selected 限制索引重用,仍会产生数值相同的排列。
顶部 state 有三个空槽。蓝色方块表示第一个 1,青色表示第二个 1,紫色表示 2。三轮选择依次填入尚未使用的索引,展开为下表的六个叶节点。第 3、4、6 项带橙色边框,汇总指向“应当去除的重复排列”。表中序号按从左到右计数,保留与重复配对关系由图中的橙框和排列数值归纳。
| 叶节点序号(从左到右) | 按元素身份区分的排列 | 图中标记与归纳 |
|---|---|---|
| 1 | [第一个 1, 第二个 1, 2] | 无橙框,保留 |
| 2 | [第一个 1, 2, 第二个 1] | 无橙框,保留 |
| 3 | [第二个 1, 第一个 1, 2] | 橙框,重复第1项 |
| 4 | [第二个 1, 2, 第一个 1] | 橙框,重复第2项 |
| 5 | [2, 第一个 1, 第二个 1] | 无橙框,保留 |
| 6 | [2, 第二个 1, 第一个 1] | 橙框,重复第5项 |
忽略区分元素身份的标记后,六个叶节点只对应 [1, 1, 2]、[1, 2, 1]、[2, 1, 1] 三种不重复的数值排列。
那么如何去除重复的排列呢?最直接地,考虑借助一个哈希集合,直接对排列结果进行去重。然而这样做不够优雅,因为生成重复排列的搜索分支没有必要,应当提前识别并剪枝,这样可以进一步提升算法效率。
1. 相等元素剪枝¶
观察图 13-8 ,在第一轮中,选择 \(1\) 或选择 \(\hat{1}\) 是等价的,在这两个选择之下生成的所有排列都是重复的。因此应该把 \(\hat{1}\) 剪枝。
同理,在第一轮选择 \(2\) 之后,第二轮选择中的 \(1\) 和 \(\hat{1}\) 也会产生重复分支,因此也应将第二轮的 \(\hat{1}\) 剪枝。
从本质上看,我们的目标是在某一轮选择中,保证多个相等的元素仅被选择一次。
图 13-8 重复排列剪枝
图解 13-8:同轮剪掉相等元素分支
在同一轮选择中对相等数值 1 只尝试一次,提前剪去重复的搜索子树。
输入数组为 choices = [1, 1, 2],索引依次为 0、1、2。下文用“第一个 1”和“第二个 1”区分索引 0 与 1;原图在第二个 1 上加帽作身份标记,两者的实际数值都为 1。
两条约束分别管索引与数值:selected 记录当前路径已用的索引;下文代码用本轮去重集合 duplicated 记录本轮未被 selected 跳过、实际选入过的数值。每次递归调用都新建自己的 duplicated;回溯恢复 selected 与 state,不删除当前调用集合中已经选入过的值。
图中只标出根 [] 与前缀 [2] 下跳过第二个 1 的两处同轮剪枝。下方“各前缀的一轮选择”表补全六个非终止前缀的取舍,其中“因已用索引跳过”列由代码规则推得,并非本图的剪枝标记;“三个唯一排列”表列出叶节点的身份顺序与实际数值。
| 当前前缀 | 保留的候选 | 因已用索引跳过 | 因同轮重复值跳过 |
|---|---|---|---|
| [] | 第一个 1、2 | 无 | 第二个 1:本轮已尝试值 1 |
| [第一个 1] | 第二个 1、2 | 第一个 1:索引 0 已在路径中 | 无 |
| [第一个 1,第二个 1] | 2 | 第一个 1、第二个 1:对应索引都已使用 | 无 |
| [第一个 1,2] | 第二个 1 | 第一个 1、2:对应索引都已使用 | 无 |
| [2] | 第一个 1 | 2:索引 2 已在路径中 | 第二个 1:本轮已尝试值 1 |
| [2,第一个 1] | 第二个 1 | 2、第一个 1:对应索引都已使用 | 无 |
| 结果序号 | 区分两个 1 的身份写法 | 实际数值结果 |
|---|---|---|
| 1 | [第一个 1,第二个 1,2] | [1,1,2] |
| 2 | [第一个 1,2,第二个 1] | [1,2,1] |
| 3 | [2,第一个 1,第二个 1] | [2,1,1] |
同一路径可以先后选用两个不同索引的 1;同一轮对数值 1 只展开一个分支。
2. 代码实现¶
在上一题的代码的基础上,我们考虑在每一轮选择中开启一个哈希集合 duplicated ,用于记录该轮中已经尝试过的元素,并将重复元素剪枝:
def backtrack(
state: list[int], choices: list[int], selected: list[bool], res: list[list[int]]
):
"""回溯算法:全排列 II"""
# 当状态长度等于元素数量时,记录解
if len(state) == len(choices):
res.append(list(state))
return
# 遍历所有选择
duplicated = set[int]()
for i, choice in enumerate(choices):
# 剪枝:不允许重复选择元素 且 不允许重复选择相等元素
if not selected[i] and choice not in duplicated:
# 尝试:做出选择,更新状态
duplicated.add(choice) # 记录选择过的元素值
selected[i] = True
state.append(choice)
# 进行下一轮选择
backtrack(state, choices, selected, res)
# 回退:撤销选择,恢复到之前的状态
selected[i] = False
state.pop()
def permutations_ii(nums: list[int]) -> list[list[int]]:
"""全排列 II"""
res = []
backtrack(state=[], choices=nums, selected=[False] * len(nums), res=res)
return res
/* 回溯算法:全排列 II */
void backtrack(vector<int> &state, const vector<int> &choices, vector<bool> &selected, vector<vector<int>> &res) {
// 当状态长度等于元素数量时,记录解
if (state.size() == choices.size()) {
res.push_back(state);
return;
}
// 遍历所有选择
unordered_set<int> duplicated;
for (int i = 0; i < choices.size(); i++) {
int choice = choices[i];
// 剪枝:不允许重复选择元素 且 不允许重复选择相等元素
if (!selected[i] && duplicated.find(choice) == duplicated.end()) {
// 尝试:做出选择,更新状态
duplicated.emplace(choice); // 记录选择过的元素值
selected[i] = true;
state.push_back(choice);
// 进行下一轮选择
backtrack(state, choices, selected, res);
// 回退:撤销选择,恢复到之前的状态
selected[i] = false;
state.pop_back();
}
}
}
/* 全排列 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;
}
/* 回溯算法:全排列 II */
void backtrack(List<Integer> state, int[] choices, boolean[] selected, List<List<Integer>> res) {
// 当状态长度等于元素数量时,记录解
if (state.size() == choices.length) {
res.add(new ArrayList<Integer>(state));
return;
}
// 遍历所有选择
Set<Integer> duplicated = new HashSet<Integer>();
for (int i = 0; i < choices.length; i++) {
int choice = choices[i];
// 剪枝:不允许重复选择元素 且 不允许重复选择相等元素
if (!selected[i] && !duplicated.contains(choice)) {
// 尝试:做出选择,更新状态
duplicated.add(choice); // 记录选择过的元素值
selected[i] = true;
state.add(choice);
// 进行下一轮选择
backtrack(state, choices, selected, res);
// 回退:撤销选择,恢复到之前的状态
selected[i] = false;
state.remove(state.size() - 1);
}
}
}
/* 全排列 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;
}
/* 回溯算法:全排列 II */
void Backtrack(List<int> state, int[] choices, bool[] selected, List<List<int>> res) {
// 当状态长度等于元素数量时,记录解
if (state.Count == choices.Length) {
res.Add(new List<int>(state));
return;
}
// 遍历所有选择
HashSet<int> duplicated = [];
for (int i = 0; i < choices.Length; i++) {
int choice = choices[i];
// 剪枝:不允许重复选择元素 且 不允许重复选择相等元素
if (!selected[i] && !duplicated.Contains(choice)) {
// 尝试:做出选择,更新状态
duplicated.Add(choice); // 记录选择过的元素值
selected[i] = true;
state.Add(choice);
// 进行下一轮选择
Backtrack(state, choices, selected, res);
// 回退:撤销选择,恢复到之前的状态
selected[i] = false;
state.RemoveAt(state.Count - 1);
}
}
}
/* 全排列 II */
List<List<int>> PermutationsII(int[] nums) {
List<List<int>> res = [];
Backtrack([], nums, new bool[nums.Length], res);
return res;
}
/* 回溯算法:全排列 II */
func backtrackII(state *[]int, choices *[]int, selected *[]bool, res *[][]int) {
// 当状态长度等于元素数量时,记录解
if len(*state) == len(*choices) {
newState := append([]int{}, *state...)
*res = append(*res, newState)
}
// 遍历所有选择
duplicated := make(map[int]struct{}, 0)
for i := 0; i < len(*choices); i++ {
choice := (*choices)[i]
// 剪枝:不允许重复选择元素 且 不允许重复选择相等元素
if _, ok := duplicated[choice]; !ok && !(*selected)[i] {
// 尝试:做出选择,更新状态
// 记录选择过的元素值
duplicated[choice] = struct{}{}
(*selected)[i] = true
*state = append(*state, choice)
// 进行下一轮选择
backtrackII(state, choices, selected, res)
// 回退:撤销选择,恢复到之前的状态
(*selected)[i] = false
*state = (*state)[:len(*state)-1]
}
}
}
/* 全排列 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
}
/* 回溯算法:全排列 II */
func backtrack(state: inout [Int], choices: [Int], selected: inout [Bool], res: inout [[Int]]) {
// 当状态长度等于元素数量时,记录解
if state.count == choices.count {
res.append(state)
return
}
// 遍历所有选择
var duplicated: Set<Int> = []
for (i, choice) in choices.enumerated() {
// 剪枝:不允许重复选择元素 且 不允许重复选择相等元素
if !selected[i], !duplicated.contains(choice) {
// 尝试:做出选择,更新状态
duplicated.insert(choice) // 记录选择过的元素值
selected[i] = true
state.append(choice)
// 进行下一轮选择
backtrack(state: &state, choices: choices, selected: &selected, res: &res)
// 回退:撤销选择,恢复到之前的状态
selected[i] = false
state.removeLast()
}
}
}
/* 全排列 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
}
/* 回溯算法:全排列 II */
function backtrack(state, choices, selected, res) {
// 当状态长度等于元素数量时,记录解
if (state.length === choices.length) {
res.push([...state]);
return;
}
// 遍历所有选择
const duplicated = new Set();
choices.forEach((choice, i) => {
// 剪枝:不允许重复选择元素 且 不允许重复选择相等元素
if (!selected[i] && !duplicated.has(choice)) {
// 尝试:做出选择,更新状态
duplicated.add(choice); // 记录选择过的元素值
selected[i] = true;
state.push(choice);
// 进行下一轮选择
backtrack(state, choices, selected, res);
// 回退:撤销选择,恢复到之前的状态
selected[i] = false;
state.pop();
}
});
}
/* 全排列 II */
function permutationsII(nums) {
const res = [];
backtrack([], nums, Array(nums.length).fill(false), res);
return res;
}
/* 回溯算法:全排列 II */
function backtrack(
state: number[],
choices: number[],
selected: boolean[],
res: number[][]
): void {
// 当状态长度等于元素数量时,记录解
if (state.length === choices.length) {
res.push([...state]);
return;
}
// 遍历所有选择
const duplicated = new Set();
choices.forEach((choice, i) => {
// 剪枝:不允许重复选择元素 且 不允许重复选择相等元素
if (!selected[i] && !duplicated.has(choice)) {
// 尝试:做出选择,更新状态
duplicated.add(choice); // 记录选择过的元素值
selected[i] = true;
state.push(choice);
// 进行下一轮选择
backtrack(state, choices, selected, res);
// 回退:撤销选择,恢复到之前的状态
selected[i] = false;
state.pop();
}
});
}
/* 全排列 II */
function permutationsII(nums: number[]): number[][] {
const res: number[][] = [];
backtrack([], nums, Array(nums.length).fill(false), res);
return res;
}
/* 回溯算法:全排列 II */
void backtrack(
List<int> state,
List<int> choices,
List<bool> selected,
List<List<int>> res,
) {
// 当状态长度等于元素数量时,记录解
if (state.length == choices.length) {
res.add(List.from(state));
return;
}
// 遍历所有选择
Set<int> duplicated = {};
for (int i = 0; i < choices.length; i++) {
int choice = choices[i];
// 剪枝:不允许重复选择元素 且 不允许重复选择相等元素
if (!selected[i] && !duplicated.contains(choice)) {
// 尝试:做出选择,更新状态
duplicated.add(choice); // 记录选择过的元素值
selected[i] = true;
state.add(choice);
// 进行下一轮选择
backtrack(state, choices, selected, res);
// 回退:撤销选择,恢复到之前的状态
selected[i] = false;
state.removeLast();
}
}
}
/* 全排列 II */
List<List<int>> permutationsII(List<int> nums) {
List<List<int>> res = [];
backtrack([], nums, List.filled(nums.length, false), res);
return res;
}
/* 回溯算法:全排列 II */
fn backtrack(mut state: Vec<i32>, choices: &[i32], selected: &mut [bool], res: &mut Vec<Vec<i32>>) {
// 当状态长度等于元素数量时,记录解
if state.len() == choices.len() {
res.push(state);
return;
}
// 遍历所有选择
let mut duplicated = HashSet::<i32>::new();
for i in 0..choices.len() {
let choice = choices[i];
// 剪枝:不允许重复选择元素 且 不允许重复选择相等元素
if !selected[i] && !duplicated.contains(&choice) {
// 尝试:做出选择,更新状态
duplicated.insert(choice); // 记录选择过的元素值
selected[i] = true;
state.push(choice);
// 进行下一轮选择
backtrack(state.clone(), choices, selected, res);
// 回退:撤销选择,恢复到之前的状态
selected[i] = false;
state.pop();
}
}
}
/* 全排列 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
}
/* 回溯算法:全排列 II */
void backtrack(int *state, int stateSize, int *choices, int choicesSize, bool *selected, int **res, int *resSize) {
// 当状态长度等于元素数量时,记录解
if (stateSize == choicesSize) {
res[*resSize] = (int *)malloc(choicesSize * sizeof(int));
for (int i = 0; i < choicesSize; i++) {
res[*resSize][i] = state[i];
}
(*resSize)++;
return;
}
// 遍历所有选择
bool duplicated[MAX_SIZE] = {false};
for (int i = 0; i < choicesSize; i++) {
int choice = choices[i];
// 剪枝:不允许重复选择元素 且 不允许重复选择相等元素
if (!selected[i] && !duplicated[choice]) {
// 尝试:做出选择,更新状态
duplicated[choice] = true; // 记录选择过的元素值
selected[i] = true;
state[stateSize] = choice;
// 进行下一轮选择
backtrack(state, stateSize + 1, choices, choicesSize, selected, res, resSize);
// 回退:撤销选择,恢复到之前的状态
selected[i] = false;
}
}
}
/* 全排列 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;
}
/* 回溯算法:全排列 II */
fun backtrack(
state: MutableList<Int>,
choices: IntArray,
selected: BooleanArray,
res: MutableList<MutableList<Int>?>
) {
// 当状态长度等于元素数量时,记录解
if (state.size == choices.size) {
res.add(state.toMutableList())
return
}
// 遍历所有选择
val duplicated = HashSet<Int>()
for (i in choices.indices) {
val choice = choices[i]
// 剪枝:不允许重复选择元素 且 不允许重复选择相等元素
if (!selected[i] && !duplicated.contains(choice)) {
// 尝试:做出选择,更新状态
duplicated.add(choice) // 记录选择过的元素值
selected[i] = true
state.add(choice)
// 进行下一轮选择
backtrack(state, choices, selected, res)
// 回退:撤销选择,恢复到之前的状态
selected[i] = false
state.removeAt(state.size - 1)
}
}
}
/* 全排列 II */
fun permutationsII(nums: IntArray): MutableList<MutableList<Int>?> {
val res = mutableListOf<MutableList<Int>?>()
backtrack(mutableListOf(), nums, BooleanArray(nums.size), res)
return res
}
### 回溯算法:全排列 II ###
def backtrack(state, choices, selected, res)
# 当状态长度等于元素数量时,记录解
if state.length == choices.length
res << state.dup
return
end
# 遍历所有选择
duplicated = Set.new
choices.each_with_index do |choice, i|
# 剪枝:不允许重复选择元素 且 不允许重复选择相等元素
if !selected[i] && !duplicated.include?(choice)
# 尝试:做出选择,更新状态
duplicated.add(choice)
selected[i] = true
state << choice
# 进行下一轮选择
backtrack(state, choices, selected, res)
# 回退:撤销选择,恢复到之前的状态
selected[i] = false
state.pop
end
end
end
### 全排列 II ###
def permutations_ii(nums)
res = []
backtrack([], nums, Array.new(nums.length, false), res)
res
end
可视化运行
假设元素两两之间互不相同,则 \(n\) 个元素共有 \(n!\) 种排列(阶乘);在记录结果时,需要复制长度为 \(n\) 的列表,使用 \(O(n)\) 时间。因此时间复杂度为 \(O(n!n)\) 。
最大递归深度为 \(n\) ,使用 \(O(n)\) 栈帧空间。selected 使用 \(O(n)\) 空间。同一时刻最多共有 \(n\) 个 duplicated ,使用 \(O(n^2)\) 空间。因此空间复杂度为 \(O(n^2)\) 。
3. 两种剪枝对比¶
请注意,虽然 selected 和 duplicated 都用于剪枝,但两者的目标不同。
- 重复选择剪枝:整个搜索过程中只有一个
selected。它记录的是当前状态中包含哪些元素,其作用是避免某个元素在state中重复出现。 - 相等元素剪枝:每轮选择(每个调用的
backtrack函数)都包含一个duplicated。它记录的是在本轮遍历(for循环)中哪些元素已被选择过,其作用是保证相等元素只被选择一次。
图 13-9 展示了两个剪枝条件的生效范围。注意,树中的每个节点代表一个选择,从根节点到叶节点的路径上的各个节点构成一个排列。
图 13-9 两种剪枝条件的作用范围
图解 13-9:两种排列剪枝分别限制索引与数值
并列对照路径索引不重复(selected)与同轮数值不重复(duplicated)两类剪枝条件。
输入数组为 choices = [1, 1, 2],索引依次为 0、1、2。下文用“第一个 1”和“第二个 1”区分索引 0 与 1;原图在第二个 1 上加帽作身份标记,两者的实际数值都为 1。
黑剪刀表示路径索引剪枝:禁止重用当前路径已用的索引,回溯后该索引恢复可用。红剪刀表示同轮数值剪枝:duplicated 只记录当前调用这一轮未被黑剪刀跳过、实际选入过的值,每次递归调用各自新建,作用域不同于 selected。
本图每个方块节点代表一次选择,表中的前缀由从根到该节点的路径串成,完整的根到叶路径构成一个排列。下方第一张表将图中的黑、红剪刀分别归入两列;一格列出多个候选时,对应多个被剪分支。根 [] 与前缀 [2] 下的第二个 1 被红剪刀剪去,其余已用索引的分支由黑剪刀剪去。第二张表按序号列出三个唯一排列。
| 当前前缀 | 保留的候选 | 黑剪刀:因已用索引跳过 | 红剪刀:因同轮重复值跳过 |
|---|---|---|---|
| [] | 第一个 1、2 | 无 | 第二个 1:本轮已尝试值 1 |
| [第一个 1] | 第二个 1、2 | 第一个 1:索引 0 已在路径中 | 无 |
| [第一个 1,第二个 1] | 2 | 第一个 1、第二个 1:对应索引都已使用 | 无 |
| [第一个 1,2] | 第二个 1 | 第一个 1、2:对应索引都已使用 | 无 |
| [2] | 第一个 1 | 2:索引 2 已在路径中 | 第二个 1:本轮已尝试值 1 |
| [2,第一个 1] | 第二个 1 | 2、第一个 1:对应索引都已使用 | 无 |
| 结果序号 | 区分两个 1 的身份写法 | 实际数值结果 |
|---|---|---|
| 1 | [第一个 1,第二个 1,2] | [1,1,2] |
| 2 | [第一个 1,2,第二个 1] | [1,2,1] |
| 3 | [2,第一个 1,第二个 1] | [2,1,1] |
同一路径可以先后选用两个不同索引的 1;同一轮对数值 1 只展开一个分支。