From e53eef69304ca9037f9558c1a753c5419edcf5fc Mon Sep 17 00:00:00 2001 From: rongyi Date: Mon, 20 May 2024 15:26:41 +0800 Subject: [PATCH] Fix panic template --- .../preorder_traversal_iii_template.rs | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/codes/rust/chapter_backtracking/preorder_traversal_iii_template.rs b/codes/rust/chapter_backtracking/preorder_traversal_iii_template.rs index f100f23cc..8be605238 100644 --- a/codes/rust/chapter_backtracking/preorder_traversal_iii_template.rs +++ b/codes/rust/chapter_backtracking/preorder_traversal_iii_template.rs @@ -11,7 +11,7 @@ use tree_node::{vec_to_tree, TreeNode}; /* 判断当前状态是否为解 */ fn is_solution(state: &mut Vec>>) -> bool { - return !state.is_empty() && state.get(state.len() - 1).unwrap().borrow().val == 7; + return !state.is_empty() && state.last().unwrap().borrow().val == 7; } /* 记录解 */ @@ -23,8 +23,8 @@ fn record_solution( } /* 判断在当前状态下,该选择是否合法 */ -fn is_valid(_: &mut Vec>>, choice: Rc>) -> bool { - return choice.borrow().val != 3; +fn is_valid(_: &mut Vec>>, choice: Option<&Rc>>) -> bool { + return choice.is_some() && choice.unwrap().borrow().val != 3; } /* 更新状态 */ @@ -34,13 +34,13 @@ fn make_choice(state: &mut Vec>>, choice: Rc>>, _: Rc>) { - state.remove(state.len() - 1); + state.pop(); } /* 回溯算法:例题三 */ fn backtrack( state: &mut Vec>>, - choices: &mut Vec>>, + choices: &Vec>>>, res: &mut Vec>>>, ) { // 检查是否为解 @@ -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()); } } } @@ -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 {