This commit is contained in:
krahets
2023-07-26 10:57:40 +08:00
parent 6381f16506
commit f8f7086196
52 changed files with 4032 additions and 0 deletions

View File

@@ -361,6 +361,41 @@ comments: true
[class]{}-[func]{permutationsI}
```
=== "Rust"
```rust title="permutations_i.rs"
/* 回溯算法:全排列 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.remove(state.len() - 1);
}
}
}
/* 全排列 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
}
```
## 13.2.2. &nbsp; 考虑相等元素的情况
!!! question
@@ -718,6 +753,43 @@ comments: true
[class]{}-[func]{permutationsII}
```
=== "Rust"
```rust title="permutations_ii.rs"
/* 回溯算法:全排列 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.remove(state.len() - 1);
}
}
}
/* 全排列 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
}
```
假设元素两两之间互不相同,则 $n$ 个元素共有 $n!$ 种排列(阶乘);在记录结果时,需要复制长度为 $n$ 的列表,使用 $O(n)$ 时间。因此,**时间复杂度为 $O(n!n)$** 。
最大递归深度为 $n$ ,使用 $O(n)$ 栈帧空间。`selected` 使用 $O(n)$ 空间。同一时刻最多共有 $n$ 个 `duplicated` ,使用 $O(n^2)$ 空间。**因此空间复杂度为 $O(n^2)$** 。