Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Rust] make rust part more idomatic and fix panic of backtrack template #1370

Merged
merged 3 commits into from
May 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion codes/rust/chapter_array_and_linkedlist/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ fn find(nums: &[i32], target: i32) -> Option<usize> {
fn main() {
/* 初始化数组 */
let arr: [i32; 5] = [0; 5];
let slice: &[i32] = &[0; 5];
print!("数组 arr = ");
print_util::print_array(&arr);
// 在 Rust 中,指定长度时([i32; 5])为数组,不指定长度时(&[i32])为切片
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use std::{cell::RefCell, rc::Rc};
use tree_node::{vec_to_tree, TreeNode};

/* 前序遍历:例题一 */
fn pre_order(res: &mut Vec<Rc<RefCell<TreeNode>>>, root: Option<Rc<RefCell<TreeNode>>>) {
fn pre_order(res: &mut Vec<Rc<RefCell<TreeNode>>>, root: Option<&Rc<RefCell<TreeNode>>>) {
if root.is_none() {
return;
}
Expand All @@ -19,8 +19,8 @@ fn pre_order(res: &mut Vec<Rc<RefCell<TreeNode>>>, root: Option<Rc<RefCell<TreeN
// 记录解
res.push(node.clone());
}
pre_order(res, node.borrow().left.clone());
pre_order(res, node.borrow().right.clone());
pre_order(res, node.borrow().left.as_ref());
pre_order(res, node.borrow().right.as_ref());
}
}

Expand All @@ -32,7 +32,7 @@ pub fn main() {

// 前序遍历
let mut res = Vec::new();
pre_order(&mut res, root);
pre_order(&mut res, root.as_ref());

println!("\n输出所有值为 7 的节点");
let mut vals = Vec::new();
Expand Down
10 changes: 5 additions & 5 deletions codes/rust/chapter_backtracking/preorder_traversal_ii_compact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use tree_node::{vec_to_tree, TreeNode};
fn pre_order(
res: &mut Vec<Vec<Rc<RefCell<TreeNode>>>>,
path: &mut Vec<Rc<RefCell<TreeNode>>>,
root: Option<Rc<RefCell<TreeNode>>>,
root: Option<&Rc<RefCell<TreeNode>>>,
) {
if root.is_none() {
return;
Expand All @@ -25,10 +25,10 @@ fn pre_order(
// 记录解
res.push(path.clone());
}
pre_order(res, path, node.borrow().left.clone());
pre_order(res, path, node.borrow().right.clone());
pre_order(res, path, node.borrow().left.as_ref());
pre_order(res, path, node.borrow().right.as_ref());
// 回退
path.remove(path.len() - 1);
path.pop();
}
}

Expand All @@ -41,7 +41,7 @@ pub fn main() {
// 前序遍历
let mut path = Vec::new();
let mut res = Vec::new();
pre_order(&mut res, &mut path, root);
pre_order(&mut res, &mut path, root.as_ref());

println!("\n输出所有根节点到节点 7 的路径");
for path in res {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use tree_node::{vec_to_tree, TreeNode};
fn pre_order(
res: &mut Vec<Vec<Rc<RefCell<TreeNode>>>>,
path: &mut Vec<Rc<RefCell<TreeNode>>>,
root: Option<Rc<RefCell<TreeNode>>>,
root: Option<&Rc<RefCell<TreeNode>>>,
) {
// 剪枝
if root.is_none() || root.as_ref().unwrap().borrow().val == 3 {
Expand All @@ -26,10 +26,10 @@ fn pre_order(
// 记录解
res.push(path.clone());
}
pre_order(res, path, node.borrow().left.clone());
pre_order(res, path, node.borrow().right.clone());
pre_order(res, path, node.borrow().left.as_ref());
pre_order(res, path, node.borrow().right.as_ref());
// 回退
path.remove(path.len() - 1);
path.pop();
}
}

Expand All @@ -42,7 +42,7 @@ pub fn main() {
// 前序遍历
let mut path = Vec::new();
let mut res = Vec::new();
pre_order(&mut res, &mut path, root);
pre_order(&mut res, &mut path, root.as_ref());

println!("\n输出所有根节点到节点 7 的路径,路径中不包含值为 3 的节点");
for path in res {
Expand Down
26 changes: 13 additions & 13 deletions codes/rust/chapter_backtracking/preorder_traversal_iii_template.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use tree_node::{vec_to_tree, TreeNode};

/* 判断当前状态是否为解 */
fn is_solution(state: &mut Vec<Rc<RefCell<TreeNode>>>) -> bool {
return !state.is_empty() && state.get(state.len() - 1).unwrap().borrow().val == 7;
return !state.is_empty() && state.last().unwrap().borrow().val == 7;
}

/* 记录解 */
Expand All @@ -23,8 +23,8 @@ fn record_solution(
}

/* 判断在当前状态下,该选择是否合法 */
fn is_valid(_: &mut Vec<Rc<RefCell<TreeNode>>>, choice: Rc<RefCell<TreeNode>>) -> bool {
return choice.borrow().val != 3;
fn is_valid(_: &mut Vec<Rc<RefCell<TreeNode>>>, choice: Option<&Rc<RefCell<TreeNode>>>) -> bool {
return choice.is_some() && choice.unwrap().borrow().val != 3;
}

/* 更新状态 */
Expand All @@ -34,13 +34,13 @@ fn make_choice(state: &mut Vec<Rc<RefCell<TreeNode>>>, choice: Rc<RefCell<TreeNo

/* 恢复状态 */
fn undo_choice(state: &mut Vec<Rc<RefCell<TreeNode>>>, _: Rc<RefCell<TreeNode>>) {
state.remove(state.len() - 1);
state.pop();
}

/* 回溯算法:例题三 */
fn backtrack(
state: &mut Vec<Rc<RefCell<TreeNode>>>,
choices: &mut Vec<Rc<RefCell<TreeNode>>>,
choices: &Vec<Option<&Rc<RefCell<TreeNode>>>>,
res: &mut Vec<Vec<Rc<RefCell<TreeNode>>>>,
) {
// 检查是否为解
Expand All @@ -49,22 +49,22 @@ fn backtrack(
record_solution(state, res);
}
// 遍历所有选择
for choice in choices {
for &choice in choices.iter() {
// 剪枝:检查选择是否合法
if is_valid(state, choice.clone()) {
if is_valid(state, choice) {
// 尝试:做出选择,更新状态
make_choice(state, choice.clone());
make_choice(state, choice.unwrap().clone());
// 进行下一轮选择
backtrack(
state,
&mut vec![
choice.borrow().left.clone().unwrap(),
choice.borrow().right.clone().unwrap(),
&vec![
choice.unwrap().borrow().left.as_ref(),
choice.unwrap().borrow().right.as_ref(),
],
res,
);
// 回退:撤销选择,恢复到之前的状态
undo_choice(state, choice.clone());
undo_choice(state, choice.unwrap().clone());
}
}
}
Expand All @@ -77,7 +77,7 @@ pub fn main() {

// 回溯算法
let mut res = Vec::new();
backtrack(&mut Vec::new(), &mut vec![root.unwrap()], &mut res);
backtrack(&mut Vec::new(), &mut vec![root.as_ref()], &mut res);

println!("\n输出所有根节点到节点 7 的路径,要求路径中不包含值为 3 的节点");
for path in res {
Expand Down