mirror of
https://github.com/krahets/hello-algo.git
synced 2026-07-13 07:46:06 +00:00
build
This commit is contained in:
@@ -165,6 +165,25 @@ comments: true
|
||||
[class]{}-[func]{preOrder}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="preorder_traversal_i_compact.rs"
|
||||
/* 前序遍历:例题一 */
|
||||
fn pre_order(res: &mut Vec<Rc<RefCell<TreeNode>>>, root: Option<Rc<RefCell<TreeNode>>>) {
|
||||
if root.is_none() {
|
||||
return;
|
||||
}
|
||||
if let Some(node) = root {
|
||||
if node.borrow().val == 7 {
|
||||
// 记录解
|
||||
res.push(node.clone());
|
||||
}
|
||||
pre_order(res, node.borrow().left.clone());
|
||||
pre_order(res, node.borrow().right.clone());
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||

|
||||
|
||||
<p align="center"> Fig. 在前序遍历中搜索节点 </p>
|
||||
@@ -370,6 +389,29 @@ comments: true
|
||||
[class]{}-[func]{preOrder}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="preorder_traversal_ii_compact.rs"
|
||||
/* 前序遍历:例题二 */
|
||||
fn pre_order(res: &mut Vec<Vec<Rc<RefCell<TreeNode>>>>, path: &mut Vec<Rc<RefCell<TreeNode>>>, root: Option<Rc<RefCell<TreeNode>>>) {
|
||||
if root.is_none() {
|
||||
return;
|
||||
}
|
||||
if let Some(node) = root {
|
||||
// 尝试
|
||||
path.push(node.clone());
|
||||
if node.borrow().val == 7 {
|
||||
// 记录解
|
||||
res.push(path.clone());
|
||||
}
|
||||
pre_order(res, path, node.borrow().left.clone());
|
||||
pre_order(res, path, node.borrow().right.clone());
|
||||
// 回退
|
||||
path.remove(path.len() - 1);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
在每次“尝试”中,我们通过将当前节点添加进 `path` 来记录路径;而在“回退”前,我们需要将该节点从 `path` 中弹出,**以恢复本次尝试之前的状态**。
|
||||
|
||||
观察该过程,**我们可以将尝试和回退理解为“前进”与“撤销”**,两个操作是互为逆向的。
|
||||
@@ -628,6 +670,32 @@ comments: true
|
||||
[class]{}-[func]{preOrder}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="preorder_traversal_iii_compact.rs"
|
||||
/* 前序遍历:例题三 */
|
||||
fn pre_order(res: &mut Vec<Vec<Rc<RefCell<TreeNode>>>>, path: &mut Vec<Rc<RefCell<TreeNode>>>, root: Option<Rc<RefCell<TreeNode>>>) {
|
||||
// 剪枝
|
||||
if root.is_none() || root.as_ref().unwrap().borrow().val == 3 {
|
||||
return;
|
||||
}
|
||||
if let Some(node) = root {
|
||||
// 尝试
|
||||
path.push(node.clone());
|
||||
if node.borrow().val == 7 {
|
||||
// 记录解
|
||||
res.push(path.clone());
|
||||
path.remove(path.len() - 1);
|
||||
return;
|
||||
}
|
||||
pre_order(res, path, node.borrow().left.clone());
|
||||
pre_order(res, path, node.borrow().right.clone());
|
||||
// 回退
|
||||
path.remove(path.len() - 1);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
剪枝是一个非常形象的名词。在搜索过程中,**我们“剪掉”了不满足约束条件的搜索分支**,避免许多无意义的尝试,从而实现搜索效率的提高。
|
||||
|
||||

|
||||
@@ -902,6 +970,12 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title=""
|
||||
|
||||
```
|
||||
|
||||
接下来,我们基于框架代码来解决例题三。状态 `state` 为节点遍历路径,选择 `choices` 为当前节点的左子节点和右子节点,结果 `res` 是路径列表。
|
||||
|
||||
=== "Java"
|
||||
@@ -1351,6 +1425,56 @@ comments: true
|
||||
[class]{}-[func]{backtrack}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="preorder_traversal_iii_template.rs"
|
||||
/* 判断当前状态是否为解 */
|
||||
fn is_solution(state: &mut Vec<Rc<RefCell<TreeNode>>>) -> bool {
|
||||
return !state.is_empty() && state.get(state.len() - 1).unwrap().borrow().val == 7;
|
||||
}
|
||||
|
||||
/* 记录解 */
|
||||
fn record_solution(state: &mut Vec<Rc<RefCell<TreeNode>>>, res: &mut Vec<Vec<Rc<RefCell<TreeNode>>>>) {
|
||||
res.push(state.clone());
|
||||
}
|
||||
|
||||
/* 判断在当前状态下,该选择是否合法 */
|
||||
fn is_valid(_: &mut Vec<Rc<RefCell<TreeNode>>>, choice: Rc<RefCell<TreeNode>>) -> bool {
|
||||
return choice.borrow().val != 3;
|
||||
}
|
||||
|
||||
/* 更新状态 */
|
||||
fn make_choice(state: &mut Vec<Rc<RefCell<TreeNode>>>, choice: Rc<RefCell<TreeNode>>) {
|
||||
state.push(choice);
|
||||
}
|
||||
|
||||
/* 恢复状态 */
|
||||
fn undo_choice(state: &mut Vec<Rc<RefCell<TreeNode>>>, _: Rc<RefCell<TreeNode>>) {
|
||||
state.remove(state.len() - 1);
|
||||
}
|
||||
|
||||
/* 回溯算法:例题三 */
|
||||
fn backtrack(state: &mut Vec<Rc<RefCell<TreeNode>>>, choices: &mut Vec<Rc<RefCell<TreeNode>>>, res: &mut Vec<Vec<Rc<RefCell<TreeNode>>>>) {
|
||||
// 检查是否为解
|
||||
if is_solution(state) {
|
||||
// 记录解
|
||||
record_solution(state, res);
|
||||
}
|
||||
// 遍历所有选择
|
||||
for choice in choices {
|
||||
// 剪枝:检查选择是否合法
|
||||
if is_valid(state, choice.clone()) {
|
||||
// 尝试:做出选择,更新状态
|
||||
make_choice(state, choice.clone());
|
||||
// 进行下一轮选择
|
||||
backtrack(state, &mut vec![choice.borrow().left.clone().unwrap(), choice.borrow().right.clone().unwrap()], res);
|
||||
// 回退:撤销选择,恢复到之前的状态
|
||||
undo_choice(state, choice.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
根据题意,当找到值为 7 的节点后应该继续搜索,**因此我们需要将记录解之后的 `return` 语句删除**。下图对比了保留或删除 `return` 语句的搜索过程。
|
||||
|
||||

|
||||
|
||||
@@ -506,6 +506,62 @@ comments: true
|
||||
[class]{}-[func]{nQueens}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="n_queens.rs"
|
||||
/* 回溯算法:N 皇后 */
|
||||
fn backtrack(row: usize, n: usize, state: &mut Vec<Vec<String>>, res: &mut Vec<Vec<Vec<String>>>,
|
||||
cols: &mut [bool], diags1: &mut [bool], diags2: &mut [bool]) {
|
||||
// 当放置完所有行时,记录解
|
||||
if row == n {
|
||||
let mut copy_state: Vec<Vec<String>> = Vec::new();
|
||||
for s_row in state.clone() {
|
||||
copy_state.push(s_row);
|
||||
}
|
||||
res.push(copy_state);
|
||||
return;
|
||||
}
|
||||
// 遍历所有列
|
||||
for col in 0..n {
|
||||
// 计算该格子对应的主对角线和副对角线
|
||||
let diag1 = row + n - 1 - col;
|
||||
let diag2 = row + col;
|
||||
// 剪枝:不允许该格子所在列、主对角线、副对角线存在皇后
|
||||
if !cols[col] && !diags1[diag1] && !diags2[diag2] {
|
||||
// 尝试:将皇后放置在该格子
|
||||
state.get_mut(row).unwrap()[col] = "Q".into();
|
||||
(cols[col], diags1[diag1], diags2[diag2]) = (true, true, true);
|
||||
// 放置下一行
|
||||
backtrack(row + 1, n, state, res, cols, diags1, diags2);
|
||||
// 回退:将该格子恢复为空位
|
||||
state.get_mut(row).unwrap()[col] = "#".into();
|
||||
(cols[col], diags1[diag1], diags2[diag2]) = (false, false, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 求解 N 皇后 */
|
||||
fn n_queens(n: usize) -> Vec<Vec<Vec<String>>> {
|
||||
// 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
|
||||
let mut state: Vec<Vec<String>> = Vec::new();
|
||||
for _ in 0..n {
|
||||
let mut row: Vec<String> = Vec::new();
|
||||
for _ in 0..n {
|
||||
row.push("#".into());
|
||||
}
|
||||
state.push(row);
|
||||
}
|
||||
let mut cols = vec![false; n]; // 记录列是否有皇后
|
||||
let mut diags1 = vec![false; 2 * n - 1]; // 记录主对角线是否有皇后
|
||||
let mut diags2 = vec![false; 2 * n - 1]; // 记录副对角线是否有皇后
|
||||
let mut res: Vec<Vec<Vec<String>>> = Vec::new();
|
||||
|
||||
backtrack(0, n, &mut state, &mut res, &mut cols, &mut diags1, &mut diags2);
|
||||
|
||||
res
|
||||
}
|
||||
```
|
||||
|
||||
逐行放置 $n$ 次,考虑列约束,则从第一行到最后一行分别有 $n, n-1, \cdots, 2, 1$ 个选择,**因此时间复杂度为 $O(n!)$** 。实际上,根据对角线约束的剪枝也能够大幅地缩小搜索空间,因而搜索效率往往优于以上时间复杂度。
|
||||
|
||||
数组 `state` 使用 $O(n^2)$ 空间,数组 `cols` , `diags1` , `diags2` 皆使用 $O(n)$ 空间。最大递归深度为 $n$ ,使用 $O(n)$ 栈帧空间。因此,**空间复杂度为 $O(n^2)$** 。
|
||||
|
||||
@@ -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. 考虑相等元素的情况
|
||||
|
||||
!!! 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)$** 。
|
||||
|
||||
@@ -273,6 +273,41 @@ comments: true
|
||||
[class]{}-[func]{subsetSumINaive}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="subset_sum_i_naive.rs"
|
||||
/* 回溯算法:子集和 I */
|
||||
fn backtrack(mut state: Vec<i32>, target: i32, total: i32, choices: &[i32], res: &mut Vec<Vec<i32>>) {
|
||||
// 子集和等于 target 时,记录解
|
||||
if total == target {
|
||||
res.push(state);
|
||||
return;
|
||||
}
|
||||
// 遍历所有选择
|
||||
for i in 0..choices.len() {
|
||||
// 剪枝:若子集和超过 target ,则跳过该选择
|
||||
if total + choices[i] > target {
|
||||
continue;
|
||||
}
|
||||
// 尝试:做出选择,更新元素和 total
|
||||
state.push(choices[i]);
|
||||
// 进行下一轮选择
|
||||
backtrack(state.clone(), target, total + choices[i], choices, res);
|
||||
// 回退:撤销选择,恢复到之前的状态
|
||||
state.pop();
|
||||
}
|
||||
}
|
||||
|
||||
/* 求解子集和 I(包含重复子集) */
|
||||
fn subset_sum_i_naive(nums: &[i32], target: i32) -> Vec<Vec<i32>> {
|
||||
let state = Vec::new(); // 状态(子集)
|
||||
let total = 0; // 子集和
|
||||
let mut res = Vec::new(); // 结果列表(子集列表)
|
||||
backtrack(state, target, total, nums, &mut res);
|
||||
res
|
||||
}
|
||||
```
|
||||
|
||||
向以上代码输入数组 $[3, 4, 5]$ 和目标元素 $9$ ,输出结果为 $[3, 3, 3], [4, 5], [5, 4]$ 。**虽然成功找出了所有和为 $9$ 的子集,但其中存在重复的子集 $[4, 5]$ 和 $[5, 4]$** 。
|
||||
|
||||
这是因为搜索过程是区分选择顺序的,然而子集不区分选择顺序。如下图所示,先选 $4$ 后选 $5$ 与先选 $5$ 后选 $4$ 是两个不同的分支,但两者对应同一个子集。
|
||||
@@ -580,6 +615,44 @@ comments: true
|
||||
[class]{}-[func]{subsetSumI}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="subset_sum_i.rs"
|
||||
/* 回溯算法:子集和 I */
|
||||
fn backtrack(mut state: Vec<i32>, target: i32, choices: &[i32], start: usize, res: &mut Vec<Vec<i32>>) {
|
||||
// 子集和等于 target 时,记录解
|
||||
if target == 0 {
|
||||
res.push(state);
|
||||
return;
|
||||
}
|
||||
// 遍历所有选择
|
||||
// 剪枝二:从 start 开始遍历,避免生成重复子集
|
||||
for i in start..choices.len() {
|
||||
// 剪枝一:若子集和超过 target ,则直接结束循环
|
||||
// 这是因为数组已排序,后边元素更大,子集和一定超过 target
|
||||
if target - choices[i] < 0 {
|
||||
break;
|
||||
}
|
||||
// 尝试:做出选择,更新 target, start
|
||||
state.push(choices[i]);
|
||||
// 进行下一轮选择
|
||||
backtrack(state.clone(), target - choices[i], choices, i, res);
|
||||
// 回退:撤销选择,恢复到之前的状态
|
||||
state.pop();
|
||||
}
|
||||
}
|
||||
|
||||
/* 求解子集和 I */
|
||||
fn subset_sum_i(nums: &mut [i32], target: i32) -> Vec<Vec<i32>> {
|
||||
let state = Vec::new(); // 状态(子集)
|
||||
nums.sort(); // 对 nums 进行排序
|
||||
let start = 0; // 遍历起始点
|
||||
let mut res = Vec::new(); // 结果列表(子集列表)
|
||||
backtrack(state, target, nums, start, &mut res);
|
||||
res
|
||||
}
|
||||
```
|
||||
|
||||
如下图所示,为将数组 $[3, 4, 5]$ 和目标元素 $9$ 输入到以上代码后的整体回溯过程。
|
||||
|
||||

|
||||
@@ -903,6 +976,49 @@ comments: true
|
||||
[class]{}-[func]{subsetSumII}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="subset_sum_ii.rs"
|
||||
/* 回溯算法:子集和 II */
|
||||
fn backtrack(mut state: Vec<i32>, target: i32, choices: &[i32], start: usize, res: &mut Vec<Vec<i32>>) {
|
||||
// 子集和等于 target 时,记录解
|
||||
if target == 0 {
|
||||
res.push(state);
|
||||
return;
|
||||
}
|
||||
// 遍历所有选择
|
||||
// 剪枝二:从 start 开始遍历,避免生成重复子集
|
||||
// 剪枝三:从 start 开始遍历,避免重复选择同一元素
|
||||
for i in start..choices.len() {
|
||||
// 剪枝一:若子集和超过 target ,则直接结束循环
|
||||
// 这是因为数组已排序,后边元素更大,子集和一定超过 target
|
||||
if target - choices[i] < 0 {
|
||||
break;
|
||||
}
|
||||
// 剪枝四:如果该元素与左边元素相等,说明该搜索分支重复,直接跳过
|
||||
if i > start && choices[i] == choices[i - 1] {
|
||||
continue;
|
||||
}
|
||||
// 尝试:做出选择,更新 target, start
|
||||
state.push(choices[i]);
|
||||
// 进行下一轮选择
|
||||
backtrack(state.clone(), target - choices[i], choices, i, res);
|
||||
// 回退:撤销选择,恢复到之前的状态
|
||||
state.pop();
|
||||
}
|
||||
}
|
||||
|
||||
/* 求解子集和 II */
|
||||
fn subset_sum_ii(nums: &mut [i32], target: i32) -> Vec<Vec<i32>> {
|
||||
let state = Vec::new(); // 状态(子集)
|
||||
nums.sort(); // 对 nums 进行排序
|
||||
let start = 0; // 遍历起始点
|
||||
let mut res = Vec::new(); // 结果列表(子集列表)
|
||||
backtrack(state, target, nums, start, &mut res);
|
||||
res
|
||||
}
|
||||
```
|
||||
|
||||
下图展示了数组 $[4, 4, 5]$ 和目标元素 $9$ 的回溯过程,共包含四种剪枝操作。请你将图示与代码注释相结合,理解整个搜索过程,以及每种剪枝操作是如何工作的。
|
||||
|
||||

|
||||
|
||||
Reference in New Issue
Block a user