rust : add codes for chapter_divide_and_conquer (#621)

This commit is contained in:
sjinzh 2023-07-19 00:32:05 +08:00 committed by GitHub
parent 9ea8a73059
commit 8737fc66dd
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 157 additions and 0 deletions

View file

@ -334,5 +334,20 @@ path = "chapter_backtracking/preorder_traversal_iii_compact.rs"
name = "preorder_traversal_iii_template"
path = "chapter_backtracking/preorder_traversal_iii_template.rs"
# Run Command: cargo run --bin binary_search_recur
[[bin]]
name = "binary_search_recur"
path = "chapter_divide_and_conquer/binary_search_recur.rs"
# Run Command: cargo run --bin hanota
[[bin]]
name = "hanota"
path = "chapter_divide_and_conquer/hanota.rs"
# Run Command: cargo run --bin build_tree
[[bin]]
name = "build_tree"
path = "chapter_divide_and_conquer/build_tree.rs"
[dependencies]
rand = "0.8.5"

View file

@ -0,0 +1,39 @@
/*
* File: binary_search_recur.rs
* Created Time: 2023-07-15
* Author: sjinzh (sjinzh@gmail.com)
*/
/* 二分查找:问题 f(i, j) */
fn dfs(nums: &[i32], target: i32, i: i32, j: i32) -> i32 {
// 若区间为空,代表无目标元素,则返回 -1
if i > j { return -1; }
let m: i32 = (i + j) / 2;
if nums[m as usize] < target {
// 递归子问题 f(m+1, j)
return dfs(nums, target, m + 1, j);
} else if nums[m as usize] > target {
// 递归子问题 f(i, m-1)
return dfs(nums, target, i, m - 1);
} else {
// 找到目标元素,返回其索引
return m;
}
}
/* 二分查找 */
fn binary_search(nums: &[i32], target: i32) -> i32 {
let n = nums.len() as i32;
// 求解问题 f(0, n-1)
dfs(nums, target, 0, n - 1)
}
/* Driver Code */
pub fn main() {
let target = 6;
let nums = [ 1, 3, 6, 8, 12, 15, 23, 26, 31, 35 ];
// 二分查找(双闭区间)
let index = binary_search(&nums, target);
println!("目标元素 6 的索引 = {index}");
}

View file

@ -0,0 +1,50 @@
/*
* File: build_tree.rs
* Created Time: 2023-07-15
* Author: sjinzh (sjinzh@gmail.com)
*/
use std::{cell::RefCell, rc::Rc};
use std::collections::HashMap;
include!("../include/include.rs");
use tree_node::TreeNode;
/* 构建二叉树:分治 */
fn dfs(preorder: &[i32], inorder: &[i32], hmap: &HashMap<i32, i32>, i: i32, l: i32, r: i32) -> Option<Rc<RefCell<TreeNode>>> {
// 子树区间为空时终止
if r - l < 0 { return None; }
// 初始化根节点
let root = TreeNode::new(preorder[i as usize]);
// 查询 m ,从而划分左右子树
let m = hmap.get(&preorder[i as usize]).unwrap();
// 子问题:构建左子树
root.borrow_mut().left = dfs(preorder, inorder, hmap, i + 1, l, m - 1);
// 子问题:构建右子树
root.borrow_mut().right = dfs(preorder, inorder, hmap, i + 1 + m - l, m + 1, r);
// 返回根节点
Some(root)
}
/* 构建二叉树 */
fn build_tree(preorder: &[i32], inorder: &[i32]) -> Option<Rc<RefCell<TreeNode>>> {
// 初始化哈希表,存储 inorder 元素到索引的映射
let mut hmap: HashMap<i32, i32> = HashMap::new();
for i in 0..inorder.len() {
hmap.insert(inorder[i], i as i32);
}
let root = dfs(preorder, inorder, &hmap, 0, 0, inorder.len() as i32 - 1);
root
}
/* Driver Code */
fn main() {
let preorder = [ 3, 9, 2, 1, 7 ];
let inorder = [ 9, 3, 1, 2, 7 ];
println!("中序遍历 = {:?}", preorder);
println!("前序遍历 = {:?}", inorder);
let root = build_tree(&preorder, &inorder);
println!("构建的二叉树为:");
print_util::print_tree(root.as_ref().unwrap());
}

View file

@ -0,0 +1,53 @@
/*
* File: hanota.rs
* Created Time: 2023-07-15
* Author: sjinzh (sjinzh@gmail.com)
*/
/* 移动一个圆盘 */
fn move_pan(src: &mut Vec<i32>, tar: &mut Vec<i32>) {
// 从 src 顶部拿出一个圆盘
let pan = src.remove(src.len() - 1);
// 将圆盘放入 tar 顶部
tar.push(pan);
}
/* 求解汉诺塔:问题 f(i) */
fn dfs(i: i32, src: &mut Vec<i32>, buf: &mut Vec<i32>, tar: &mut Vec<i32>) {
// 若 src 只剩下一个圆盘,则直接将其移到 tar
if i == 1 {
move_pan(src, tar);
return;
}
// 子问题 f(i-1) :将 src 顶部 i-1 个圆盘借助 tar 移到 buf
dfs(i - 1, src, tar, buf);
// 子问题 f(1) :将 src 剩余一个圆盘移到 tar
move_pan(src, tar);
// 子问题 f(i-1) :将 buf 顶部 i-1 个圆盘借助 src 移到 tar
dfs(i - 1, buf, src, tar);
}
/* 求解汉诺塔 */
fn hanota(A: &mut Vec<i32>, B: &mut Vec<i32>, C: &mut Vec<i32>) {
let n = A.len() as i32;
// 将 A 顶部 n 个圆盘借助 B 移到 C
dfs(n, A, B, C);
}
/* Driver Code */
pub fn main() {
let mut A = vec![5, 4, 3, 2, 1];
let mut B = Vec::new();
let mut C = Vec::new();
println!("初始状态下:");
println!("A = {:?}", A);
println!("B = {:?}", B);
println!("C = {:?}", C);
hanota(&mut A, &mut B, &mut C);
println!("圆盘移动完成后:");
println!("A = {:?}", A);
println!("B = {:?}", B);
println!("C = {:?}", C);
}