mirror of
https://github.com/krahets/hello-algo.git
synced 2026-07-15 08:26:06 +00:00
build
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -52,6 +52,97 @@ comments: true
|
||||
|
||||
请注意,$n$ 维方阵中 $row - col$ 的范围是 $[-n + 1, n - 1]$ ,$row + col$ 的范围是 $[0, 2n - 2]$ ,所以主对角线和次对角线的数量都为 $2n - 1$ ,即数组 `diag1` 和 `diag2` 的长度都为 $2n - 1$ 。
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="n_queens.py"
|
||||
def backtrack(
|
||||
row: int,
|
||||
n: int,
|
||||
state: list[list[str]],
|
||||
res: list[list[list[str]]],
|
||||
cols: list[bool],
|
||||
diags1: list[bool],
|
||||
diags2: list[bool],
|
||||
):
|
||||
"""回溯算法:N 皇后"""
|
||||
# 当放置完所有行时,记录解
|
||||
if row == n:
|
||||
res.append([list(row) for row in state])
|
||||
return
|
||||
# 遍历所有列
|
||||
for col in range(n):
|
||||
# 计算该格子对应的主对角线和副对角线
|
||||
diag1 = row - col + n - 1
|
||||
diag2 = row + col
|
||||
# 剪枝:不允许该格子所在列、主对角线、副对角线存在皇后
|
||||
if not cols[col] and not diags1[diag1] and not diags2[diag2]:
|
||||
# 尝试:将皇后放置在该格子
|
||||
state[row][col] = "Q"
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = True
|
||||
# 放置下一行
|
||||
backtrack(row + 1, n, state, res, cols, diags1, diags2)
|
||||
# 回退:将该格子恢复为空位
|
||||
state[row][col] = "#"
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = False
|
||||
|
||||
def n_queens(n: int) -> list[list[list[str]]]:
|
||||
"""求解 N 皇后"""
|
||||
# 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
|
||||
state = [["#" for _ in range(n)] for _ in range(n)]
|
||||
cols = [False] * n # 记录列是否有皇后
|
||||
diags1 = [False] * (2 * n - 1) # 记录主对角线是否有皇后
|
||||
diags2 = [False] * (2 * n - 1) # 记录副对角线是否有皇后
|
||||
res = []
|
||||
backtrack(0, n, state, res, cols, diags1, diags2)
|
||||
|
||||
return res
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="n_queens.cpp"
|
||||
/* 回溯算法:N 皇后 */
|
||||
void backtrack(int row, int n, vector<vector<string>> &state, vector<vector<vector<string>>> &res, vector<bool> &cols,
|
||||
vector<bool> &diags1, vector<bool> &diags2) {
|
||||
// 当放置完所有行时,记录解
|
||||
if (row == n) {
|
||||
res.push_back(state);
|
||||
return;
|
||||
}
|
||||
// 遍历所有列
|
||||
for (int col = 0; col < n; col++) {
|
||||
// 计算该格子对应的主对角线和副对角线
|
||||
int diag1 = row - col + n - 1;
|
||||
int diag2 = row + col;
|
||||
// 剪枝:不允许该格子所在列、主对角线、副对角线存在皇后
|
||||
if (!cols[col] && !diags1[diag1] && !diags2[diag2]) {
|
||||
// 尝试:将皇后放置在该格子
|
||||
state[row][col] = "Q";
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = true;
|
||||
// 放置下一行
|
||||
backtrack(row + 1, n, state, res, cols, diags1, diags2);
|
||||
// 回退:将该格子恢复为空位
|
||||
state[row][col] = "#";
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 求解 N 皇后 */
|
||||
vector<vector<vector<string>>> nQueens(int n) {
|
||||
// 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
|
||||
vector<vector<string>> state(n, vector<string>(n, "#"));
|
||||
vector<bool> cols(n, false); // 记录列是否有皇后
|
||||
vector<bool> diags1(2 * n - 1, false); // 记录主对角线是否有皇后
|
||||
vector<bool> diags2(2 * n - 1, false); // 记录副对角线是否有皇后
|
||||
vector<vector<vector<string>>> res;
|
||||
|
||||
backtrack(0, n, state, res, cols, diags1, diags2);
|
||||
|
||||
return res;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="n_queens.java"
|
||||
@@ -108,15 +199,19 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
=== "C#"
|
||||
|
||||
```cpp title="n_queens.cpp"
|
||||
```csharp title="n_queens.cs"
|
||||
/* 回溯算法:N 皇后 */
|
||||
void backtrack(int row, int n, vector<vector<string>> &state, vector<vector<vector<string>>> &res, vector<bool> &cols,
|
||||
vector<bool> &diags1, vector<bool> &diags2) {
|
||||
void backtrack(int row, int n, List<List<string>> state, List<List<List<string>>> res,
|
||||
bool[] cols, bool[] diags1, bool[] diags2) {
|
||||
// 当放置完所有行时,记录解
|
||||
if (row == n) {
|
||||
res.push_back(state);
|
||||
List<List<string>> copyState = new List<List<string>>();
|
||||
foreach (List<string> sRow in state) {
|
||||
copyState.Add(new List<string>(sRow));
|
||||
}
|
||||
res.Add(copyState);
|
||||
return;
|
||||
}
|
||||
// 遍历所有列
|
||||
@@ -139,13 +234,20 @@ comments: true
|
||||
}
|
||||
|
||||
/* 求解 N 皇后 */
|
||||
vector<vector<vector<string>>> nQueens(int n) {
|
||||
List<List<List<string>>> nQueens(int n) {
|
||||
// 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
|
||||
vector<vector<string>> state(n, vector<string>(n, "#"));
|
||||
vector<bool> cols(n, false); // 记录列是否有皇后
|
||||
vector<bool> diags1(2 * n - 1, false); // 记录主对角线是否有皇后
|
||||
vector<bool> diags2(2 * n - 1, false); // 记录副对角线是否有皇后
|
||||
vector<vector<vector<string>>> res;
|
||||
List<List<string>> state = new List<List<string>>();
|
||||
for (int i = 0; i < n; i++) {
|
||||
List<string> row = new List<string>();
|
||||
for (int j = 0; j < n; j++) {
|
||||
row.Add("#");
|
||||
}
|
||||
state.Add(row);
|
||||
}
|
||||
bool[] cols = new bool[n]; // 记录列是否有皇后
|
||||
bool[] diags1 = new bool[2 * n - 1]; // 记录主对角线是否有皇后
|
||||
bool[] diags2 = new bool[2 * n - 1]; // 记录副对角线是否有皇后
|
||||
List<List<List<string>>> res = new List<List<List<string>>>();
|
||||
|
||||
backtrack(0, n, state, res, cols, diags1, diags2);
|
||||
|
||||
@@ -153,52 +255,6 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="n_queens.py"
|
||||
def backtrack(
|
||||
row: int,
|
||||
n: int,
|
||||
state: list[list[str]],
|
||||
res: list[list[list[str]]],
|
||||
cols: list[bool],
|
||||
diags1: list[bool],
|
||||
diags2: list[bool],
|
||||
):
|
||||
"""回溯算法:N 皇后"""
|
||||
# 当放置完所有行时,记录解
|
||||
if row == n:
|
||||
res.append([list(row) for row in state])
|
||||
return
|
||||
# 遍历所有列
|
||||
for col in range(n):
|
||||
# 计算该格子对应的主对角线和副对角线
|
||||
diag1 = row - col + n - 1
|
||||
diag2 = row + col
|
||||
# 剪枝:不允许该格子所在列、主对角线、副对角线存在皇后
|
||||
if not cols[col] and not diags1[diag1] and not diags2[diag2]:
|
||||
# 尝试:将皇后放置在该格子
|
||||
state[row][col] = "Q"
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = True
|
||||
# 放置下一行
|
||||
backtrack(row + 1, n, state, res, cols, diags1, diags2)
|
||||
# 回退:将该格子恢复为空位
|
||||
state[row][col] = "#"
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = False
|
||||
|
||||
def n_queens(n: int) -> list[list[list[str]]]:
|
||||
"""求解 N 皇后"""
|
||||
# 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
|
||||
state = [["#" for _ in range(n)] for _ in range(n)]
|
||||
cols = [False] * n # 记录列是否有皇后
|
||||
diags1 = [False] * (2 * n - 1) # 记录主对角线是否有皇后
|
||||
diags2 = [False] * (2 * n - 1) # 记录副对角线是否有皇后
|
||||
res = []
|
||||
backtrack(0, n, state, res, cols, diags1, diags2)
|
||||
|
||||
return res
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="n_queens.go"
|
||||
@@ -284,6 +340,54 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="n_queens.swift"
|
||||
/* 回溯算法:N 皇后 */
|
||||
func backtrack(row: Int, n: Int, state: inout [[String]], res: inout [[[String]]], cols: inout [Bool], diags1: inout [Bool], diags2: inout [Bool]) {
|
||||
// 当放置完所有行时,记录解
|
||||
if row == n {
|
||||
res.append(state)
|
||||
return
|
||||
}
|
||||
// 遍历所有列
|
||||
for col in 0 ..< n {
|
||||
// 计算该格子对应的主对角线和副对角线
|
||||
let diag1 = row - col + n - 1
|
||||
let diag2 = row + col
|
||||
// 剪枝:不允许该格子所在列、主对角线、副对角线存在皇后
|
||||
if !cols[col] && !diags1[diag1] && !diags2[diag2] {
|
||||
// 尝试:将皇后放置在该格子
|
||||
state[row][col] = "Q"
|
||||
cols[col] = true
|
||||
diags1[diag1] = true
|
||||
diags2[diag2] = true
|
||||
// 放置下一行
|
||||
backtrack(row: row + 1, n: n, state: &state, res: &res, cols: &cols, diags1: &diags1, diags2: &diags2)
|
||||
// 回退:将该格子恢复为空位
|
||||
state[row][col] = "#"
|
||||
cols[col] = false
|
||||
diags1[diag1] = false
|
||||
diags2[diag2] = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 求解 N 皇后 */
|
||||
func nQueens(n: Int) -> [[[String]]] {
|
||||
// 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
|
||||
var state = Array(repeating: Array(repeating: "#", count: n), count: n)
|
||||
var cols = Array(repeating: false, count: n) // 记录列是否有皇后
|
||||
var diags1 = Array(repeating: false, count: 2 * n - 1) // 记录主对角线是否有皇后
|
||||
var diags2 = Array(repeating: false, count: 2 * n - 1) // 记录副对角线是否有皇后
|
||||
var res: [[[String]]] = []
|
||||
|
||||
backtrack(row: 0, n: n, state: &state, res: &res, cols: &cols, diags1: &diags1, diags2: &diags2)
|
||||
|
||||
return res
|
||||
}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="n_queens.js"
|
||||
@@ -378,126 +482,6 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="n_queens.c"
|
||||
[class]{}-[func]{backtrack}
|
||||
|
||||
[class]{}-[func]{nQueens}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="n_queens.cs"
|
||||
/* 回溯算法:N 皇后 */
|
||||
void backtrack(int row, int n, List<List<string>> state, List<List<List<string>>> res,
|
||||
bool[] cols, bool[] diags1, bool[] diags2) {
|
||||
// 当放置完所有行时,记录解
|
||||
if (row == n) {
|
||||
List<List<string>> copyState = new List<List<string>>();
|
||||
foreach (List<string> sRow in state) {
|
||||
copyState.Add(new List<string>(sRow));
|
||||
}
|
||||
res.Add(copyState);
|
||||
return;
|
||||
}
|
||||
// 遍历所有列
|
||||
for (int col = 0; col < n; col++) {
|
||||
// 计算该格子对应的主对角线和副对角线
|
||||
int diag1 = row - col + n - 1;
|
||||
int diag2 = row + col;
|
||||
// 剪枝:不允许该格子所在列、主对角线、副对角线存在皇后
|
||||
if (!cols[col] && !diags1[diag1] && !diags2[diag2]) {
|
||||
// 尝试:将皇后放置在该格子
|
||||
state[row][col] = "Q";
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = true;
|
||||
// 放置下一行
|
||||
backtrack(row + 1, n, state, res, cols, diags1, diags2);
|
||||
// 回退:将该格子恢复为空位
|
||||
state[row][col] = "#";
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 求解 N 皇后 */
|
||||
List<List<List<string>>> nQueens(int n) {
|
||||
// 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
|
||||
List<List<string>> state = new List<List<string>>();
|
||||
for (int i = 0; i < n; i++) {
|
||||
List<string> row = new List<string>();
|
||||
for (int j = 0; j < n; j++) {
|
||||
row.Add("#");
|
||||
}
|
||||
state.Add(row);
|
||||
}
|
||||
bool[] cols = new bool[n]; // 记录列是否有皇后
|
||||
bool[] diags1 = new bool[2 * n - 1]; // 记录主对角线是否有皇后
|
||||
bool[] diags2 = new bool[2 * n - 1]; // 记录副对角线是否有皇后
|
||||
List<List<List<string>>> res = new List<List<List<string>>>();
|
||||
|
||||
backtrack(0, n, state, res, cols, diags1, diags2);
|
||||
|
||||
return res;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="n_queens.swift"
|
||||
/* 回溯算法:N 皇后 */
|
||||
func backtrack(row: Int, n: Int, state: inout [[String]], res: inout [[[String]]], cols: inout [Bool], diags1: inout [Bool], diags2: inout [Bool]) {
|
||||
// 当放置完所有行时,记录解
|
||||
if row == n {
|
||||
res.append(state)
|
||||
return
|
||||
}
|
||||
// 遍历所有列
|
||||
for col in 0 ..< n {
|
||||
// 计算该格子对应的主对角线和副对角线
|
||||
let diag1 = row - col + n - 1
|
||||
let diag2 = row + col
|
||||
// 剪枝:不允许该格子所在列、主对角线、副对角线存在皇后
|
||||
if !cols[col] && !diags1[diag1] && !diags2[diag2] {
|
||||
// 尝试:将皇后放置在该格子
|
||||
state[row][col] = "Q"
|
||||
cols[col] = true
|
||||
diags1[diag1] = true
|
||||
diags2[diag2] = true
|
||||
// 放置下一行
|
||||
backtrack(row: row + 1, n: n, state: &state, res: &res, cols: &cols, diags1: &diags1, diags2: &diags2)
|
||||
// 回退:将该格子恢复为空位
|
||||
state[row][col] = "#"
|
||||
cols[col] = false
|
||||
diags1[diag1] = false
|
||||
diags2[diag2] = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 求解 N 皇后 */
|
||||
func nQueens(n: Int) -> [[[String]]] {
|
||||
// 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
|
||||
var state = Array(repeating: Array(repeating: "#", count: n), count: n)
|
||||
var cols = Array(repeating: false, count: n) // 记录列是否有皇后
|
||||
var diags1 = Array(repeating: false, count: 2 * n - 1) // 记录主对角线是否有皇后
|
||||
var diags2 = Array(repeating: false, count: 2 * n - 1) // 记录副对角线是否有皇后
|
||||
var res: [[[String]]] = []
|
||||
|
||||
backtrack(row: 0, n: n, state: &state, res: &res, cols: &cols, diags1: &diags1, diags2: &diags2)
|
||||
|
||||
return res
|
||||
}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="n_queens.zig"
|
||||
[class]{}-[func]{backtrack}
|
||||
|
||||
[class]{}-[func]{nQueens}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="n_queens.dart"
|
||||
@@ -614,6 +598,22 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="n_queens.c"
|
||||
[class]{}-[func]{backtrack}
|
||||
|
||||
[class]{}-[func]{nQueens}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="n_queens.zig"
|
||||
[class]{}-[func]{backtrack}
|
||||
|
||||
[class]{}-[func]{nQueens}
|
||||
```
|
||||
|
||||
逐行放置 $n$ 次,考虑列约束,则从第一行到最后一行分别有 $n$、$n-1$、$\dots$、$2$、$1$ 个选择,**因此时间复杂度为 $O(n!)$** 。实际上,根据对角线约束的剪枝也能够大幅地缩小搜索空间,因而搜索效率往往优于以上时间复杂度。
|
||||
|
||||
数组 `state` 使用 $O(n^2)$ 空间,数组 `cols`、`diags1` 和 `diags2` 皆使用 $O(n)$ 空间。最大递归深度为 $n$ ,使用 $O(n)$ 栈帧空间。因此,**空间复杂度为 $O(n^2)$** 。
|
||||
|
||||
@@ -55,39 +55,35 @@ comments: true
|
||||
|
||||
想清楚以上信息之后,我们就可以在框架代码中做“完形填空”了。为了缩短代码行数,我们不单独实现框架代码中的各个函数,而是将他们展开在 `backtrack()` 函数中。
|
||||
|
||||
=== "Java"
|
||||
=== "Python"
|
||||
|
||||
```java title="permutations_i.java"
|
||||
/* 回溯算法:全排列 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
```python title="permutations_i.py"
|
||||
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()
|
||||
|
||||
/* 全排列 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;
|
||||
}
|
||||
def permutations_i(nums: list[int]) -> list[list[int]]:
|
||||
"""全排列 I"""
|
||||
res = []
|
||||
backtrack(state=[], choices=nums, selected=[False] * len(nums), res=res)
|
||||
return res
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
@@ -127,35 +123,74 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
=== "Java"
|
||||
|
||||
```python title="permutations_i.py"
|
||||
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()
|
||||
```java title="permutations_i.java"
|
||||
/* 回溯算法:全排列 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
def permutations_i(nums: list[int]) -> list[list[int]]:
|
||||
"""全排列 I"""
|
||||
res = []
|
||||
backtrack(state=[], choices=nums, selected=[False] * len(nums), res=res)
|
||||
return res
|
||||
/* 全排列 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;
|
||||
}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="permutations_i.cs"
|
||||
/* 回溯算法:全排列 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 = new List<List<int>>();
|
||||
backtrack(new List<int>(), nums, new bool[nums.Length], res);
|
||||
return res;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
@@ -195,6 +230,42 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="permutations_i.swift"
|
||||
/* 回溯算法:全排列 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
|
||||
}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="permutations_i.js"
|
||||
@@ -268,136 +339,6 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="permutations_i.c"
|
||||
/* 回溯算法:全排列 I */
|
||||
void backtrack(vector *state, vector *choices, vector *selected, vector *res) {
|
||||
// 当状态长度等于元素数量时,记录解
|
||||
if (state->size == choices->size) {
|
||||
vector *newState = newVector();
|
||||
for (int i = 0; i < state->size; i++) {
|
||||
vectorPushback(newState, state->data[i], sizeof(int));
|
||||
}
|
||||
vectorPushback(res, newState, sizeof(vector));
|
||||
return;
|
||||
}
|
||||
// 遍历所有选择
|
||||
for (int i = 0; i < choices->size; i++) {
|
||||
int *choice = malloc(sizeof(int));
|
||||
*choice = *((int *)(choices->data[i]));
|
||||
// 剪枝:不允许重复选择元素 且 不允许重复选择相等元素
|
||||
bool select = *((bool *)(selected->data[i]));
|
||||
if (!select) {
|
||||
// 尝试:做出选择,更新状态
|
||||
*((bool *)selected->data[i]) = true;
|
||||
vectorPushback(state, choice, sizeof(int));
|
||||
// 进行下一轮选择
|
||||
backtrack(state, choices, selected, res);
|
||||
// 回退:撤销选择,恢复到之前的状态
|
||||
*((bool *)selected->data[i]) = false;
|
||||
vectorPopback(state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 全排列 I */
|
||||
vector *permutationsI(vector *nums) {
|
||||
vector *iState = newVector();
|
||||
|
||||
int select[3] = {false, false, false};
|
||||
vector *bSelected = newVector();
|
||||
for (int i = 0; i < nums->size; i++) {
|
||||
vectorPushback(bSelected, &select[i], sizeof(int));
|
||||
}
|
||||
|
||||
vector *res = newVector();
|
||||
|
||||
// 前序遍历
|
||||
backtrack(iState, nums, bSelected, res);
|
||||
return res;
|
||||
}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="permutations_i.cs"
|
||||
/* 回溯算法:全排列 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 = new List<List<int>>();
|
||||
backtrack(new List<int>(), nums, new bool[nums.Length], res);
|
||||
return res;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="permutations_i.swift"
|
||||
/* 回溯算法:全排列 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
|
||||
}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="permutations_i.zig"
|
||||
[class]{}-[func]{backtrack}
|
||||
|
||||
[class]{}-[func]{permutationsI}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="permutations_i.dart"
|
||||
@@ -473,6 +414,65 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="permutations_i.c"
|
||||
/* 回溯算法:全排列 I */
|
||||
void backtrack(vector *state, vector *choices, vector *selected, vector *res) {
|
||||
// 当状态长度等于元素数量时,记录解
|
||||
if (state->size == choices->size) {
|
||||
vector *newState = newVector();
|
||||
for (int i = 0; i < state->size; i++) {
|
||||
vectorPushback(newState, state->data[i], sizeof(int));
|
||||
}
|
||||
vectorPushback(res, newState, sizeof(vector));
|
||||
return;
|
||||
}
|
||||
// 遍历所有选择
|
||||
for (int i = 0; i < choices->size; i++) {
|
||||
int *choice = malloc(sizeof(int));
|
||||
*choice = *((int *)(choices->data[i]));
|
||||
// 剪枝:不允许重复选择元素 且 不允许重复选择相等元素
|
||||
bool select = *((bool *)(selected->data[i]));
|
||||
if (!select) {
|
||||
// 尝试:做出选择,更新状态
|
||||
*((bool *)selected->data[i]) = true;
|
||||
vectorPushback(state, choice, sizeof(int));
|
||||
// 进行下一轮选择
|
||||
backtrack(state, choices, selected, res);
|
||||
// 回退:撤销选择,恢复到之前的状态
|
||||
*((bool *)selected->data[i]) = false;
|
||||
vectorPopback(state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 全排列 I */
|
||||
vector *permutationsI(vector *nums) {
|
||||
vector *iState = newVector();
|
||||
|
||||
int select[3] = {false, false, false};
|
||||
vector *bSelected = newVector();
|
||||
for (int i = 0; i < nums->size; i++) {
|
||||
vectorPushback(bSelected, &select[i], sizeof(int));
|
||||
}
|
||||
|
||||
vector *res = newVector();
|
||||
|
||||
// 前序遍历
|
||||
backtrack(iState, nums, bSelected, res);
|
||||
return res;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="permutations_i.zig"
|
||||
[class]{}-[func]{backtrack}
|
||||
|
||||
[class]{}-[func]{permutationsI}
|
||||
```
|
||||
|
||||
## 13.2.2 考虑相等元素的情况
|
||||
|
||||
!!! question
|
||||
@@ -505,41 +505,37 @@ comments: true
|
||||
|
||||
在上一题的代码的基础上,我们考虑在每一轮选择中开启一个哈希表 `duplicated` ,用于记录该轮中已经尝试过的元素,并将重复元素剪枝。
|
||||
|
||||
=== "Java"
|
||||
=== "Python"
|
||||
|
||||
```java title="permutations_ii.java"
|
||||
/* 回溯算法:全排列 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
```python title="permutations_ii.py"
|
||||
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()
|
||||
|
||||
/* 全排列 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;
|
||||
}
|
||||
def permutations_ii(nums: list[int]) -> list[list[int]]:
|
||||
"""全排列 II"""
|
||||
res = []
|
||||
backtrack(state=[], choices=nums, selected=[False] * len(nums), res=res)
|
||||
return res
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
@@ -581,37 +577,78 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
=== "Java"
|
||||
|
||||
```python title="permutations_ii.py"
|
||||
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()
|
||||
```java title="permutations_ii.java"
|
||||
/* 回溯算法:全排列 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
def permutations_ii(nums: list[int]) -> list[list[int]]:
|
||||
"""全排列 II"""
|
||||
res = []
|
||||
backtrack(state=[], choices=nums, selected=[False] * len(nums), res=res)
|
||||
return res
|
||||
/* 全排列 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;
|
||||
}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="permutations_ii.cs"
|
||||
/* 回溯算法:全排列 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;
|
||||
}
|
||||
// 遍历所有选择
|
||||
ISet<int> duplicated = new HashSet<int>();
|
||||
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 = new List<List<int>>();
|
||||
backtrack(new List<int>(), nums, new bool[nums.Length], res);
|
||||
return res;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
@@ -654,6 +691,44 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="permutations_ii.swift"
|
||||
/* 回溯算法:全排列 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
|
||||
}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="permutations_ii.js"
|
||||
@@ -731,97 +806,6 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="permutations_ii.c"
|
||||
[class]{}-[func]{backtrack}
|
||||
|
||||
[class]{}-[func]{permutationsII}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="permutations_ii.cs"
|
||||
/* 回溯算法:全排列 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;
|
||||
}
|
||||
// 遍历所有选择
|
||||
ISet<int> duplicated = new HashSet<int>();
|
||||
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 = new List<List<int>>();
|
||||
backtrack(new List<int>(), nums, new bool[nums.Length], res);
|
||||
return res;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="permutations_ii.swift"
|
||||
/* 回溯算法:全排列 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
|
||||
}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="permutations_ii.zig"
|
||||
[class]{}-[func]{backtrack}
|
||||
|
||||
[class]{}-[func]{permutationsII}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="permutations_ii.dart"
|
||||
@@ -901,6 +885,22 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="permutations_ii.c"
|
||||
[class]{}-[func]{backtrack}
|
||||
|
||||
[class]{}-[func]{permutationsII}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="permutations_ii.zig"
|
||||
[class]{}-[func]{backtrack}
|
||||
|
||||
[class]{}-[func]{permutationsII}
|
||||
```
|
||||
|
||||
假设元素两两之间互不相同,则 $n$ 个元素共有 $n!$ 种排列(阶乘);在记录结果时,需要复制长度为 $n$ 的列表,使用 $O(n)$ 时间。**因此时间复杂度为 $O(n!n)$** 。
|
||||
|
||||
最大递归深度为 $n$ ,使用 $O(n)$ 栈帧空间。`selected` 使用 $O(n)$ 空间。同一时刻最多共有 $n$ 个 `duplicated` ,使用 $O(n^2)$ 空间。**因此空间复杂度为 $O(n^2)$** 。
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user