Bug fixes and improvements (#1572)

* Sync zh and zh-hant versions.

* Remove the polyfill.io link from mkdocs.yml

* Update contributors' info for code reviewers and en/zh-hant versions reviewers.

* Fix graph.md

* Update avatars for English version reviewers.

* Sync zh and zh-hant versions.

* Fix two_sum_brute_force.png

* Sync zh and zh-hant versions.
Optimize structrue of index.html.

* Format index.html
This commit is contained in:
Yudong Jin 2024-11-25 19:21:11 +08:00 committed by GitHub
parent 01a5f7b09f
commit 2a9db6d039
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
65 changed files with 414 additions and 140 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 13 KiB

View File

@ -353,4 +353,4 @@
</a>
</div>
</div>
</section>
</section>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 13 KiB

View File

@ -420,4 +420,4 @@
</a>
</div>
</div>
</section>
</section>

View File

@ -37,12 +37,12 @@ HashTable *find(HashTable *h, int key) {
}
/* 雜湊表元素插入 */
void insert(HashTable *h, int key, int val) {
HashTable *t = find(h, key);
void insert(HashTable **h, int key, int val) {
HashTable *t = find(*h, key);
if (t == NULL) {
HashTable *tmp = malloc(sizeof(HashTable));
tmp->key = key, tmp->val = val;
HASH_ADD_INT(h, key, tmp);
HASH_ADD_INT(*h, key, tmp);
} else {
t->val = val;
}
@ -59,7 +59,7 @@ int *twoSumHashTable(int *nums, int numsSize, int target, int *returnSize) {
*returnSize = 2;
return res;
}
insert(hashtable, nums[i], i);
insert(&hashtable, nums[i], i);
}
*returnSize = 0;
return NULL;
@ -83,4 +83,4 @@ int main() {
printArray(res, returnSize);
return 0;
}
}

View File

@ -65,6 +65,7 @@ void countingSort(int nums[], int size) {
// 使用結果陣列 res 覆蓋原陣列 nums
memcpy(nums, res, size * sizeof(int));
// 5. 釋放記憶體
free(res);
free(counter);
}

View File

@ -16,6 +16,7 @@ int digit(int num, int exp) {
void countingSortDigit(int nums[], int size, int exp) {
// 十進位制的位範圍為 0~9 ,因此需要長度為 10 的桶陣列
int *counter = (int *)malloc((sizeof(int) * 10));
memset(counter, 0, sizeof(int) * 10); // 初始化為 0 以支持後續記憶體釋放
// 統計 0~9 各數字的出現次數
for (int i = 0; i < size; i++) {
// 獲取 nums[i] 第 k 位,記為 d
@ -39,13 +40,16 @@ void countingSortDigit(int nums[], int size, int exp) {
for (int i = 0; i < size; i++) {
nums[i] = res[i];
}
// 釋放記憶體
free(res);
free(counter);
}
/* 基數排序 */
void radixSort(int nums[], int size) {
// 獲取陣列的最大元素,用於判斷最大位數
int max = INT32_MIN;
for (size_t i = 0; i < size - 1; i++) {
for (int i = 0; i < size; i++) {
if (nums[i] > max) {
max = nums[i];
}

View File

@ -105,7 +105,7 @@ public class min_path_sum {
// 暴力搜尋
int res = MinPathSumDFS(grid, n - 1, m - 1);
Console.WriteLine("從左上角到右下角的小路徑和為 " + res);
Console.WriteLine("從左上角到右下角的小路徑和為 " + res);
// 記憶化搜尋
int[][] mem = new int[n][];
@ -114,14 +114,14 @@ public class min_path_sum {
Array.Fill(mem[i], -1);
}
res = MinPathSumDFSMem(grid, mem, n - 1, m - 1);
Console.WriteLine("從左上角到右下角的小路徑和為 " + res);
Console.WriteLine("從左上角到右下角的小路徑和為 " + res);
// 動態規劃
res = MinPathSumDP(grid);
Console.WriteLine("從左上角到右下角的小路徑和為 " + res);
Console.WriteLine("從左上角到右下角的小路徑和為 " + res);
// 空間最佳化後的動態規劃
res = MinPathSumDPComp(grid);
Console.WriteLine("從左上角到右下角的小路徑和為 " + res);
Console.WriteLine("從左上角到右下角的小路徑和為 " + res);
}
}

View File

@ -24,8 +24,8 @@ public class heap {
/* 初始化堆積 */
// 初始化小頂堆積
PriorityQueue<int, int> minHeap = new();
// 初始化大頂堆積(使用 lambda 表示式修改 Comparator 即可)
PriorityQueue<int, int> maxHeap = new(Comparer<int>.Create((x, y) => y - x));
// 初始化大頂堆積(使用 lambda 表示式修改 Comparer 即可)
PriorityQueue<int, int> maxHeap = new(Comparer<int>.Create((x, y) => y.CompareTo(x)));
Console.WriteLine("以下測試樣例為大頂堆積");
/* 元素入堆積 */

View File

@ -103,18 +103,18 @@ void main() {
//
int res = minPathSumDFS(grid, n - 1, m - 1);
print("從左上角到右下角的小路徑和為 $res");
print("從左上角到右下角的小路徑和為 $res");
//
List<List<int>> mem = List.generate(n, (i) => List.filled(m, -1));
res = minPathSumDFSMem(grid, mem, n - 1, m - 1);
print("從左上角到右下角的小路徑和為 $res");
print("從左上角到右下角的小路徑和為 $res");
//
res = minPathSumDP(grid);
print("從左上角到右下角的小路徑和為 $res");
print("從左上角到右下角的小路徑和為 $res");
//
res = minPathSumDPComp(grid);
print("從左上角到右下角的小路徑和為 $res");
print("從左上角到右下角的小路徑和為 $res");
}

View File

@ -20,7 +20,7 @@ func TestMinPathSum(t *testing.T) {
// 暴力搜尋
res := minPathSumDFS(grid, n-1, m-1)
fmt.Printf("從左上角到右下角的小路徑和為 %d\n", res)
fmt.Printf("從左上角到右下角的小路徑和為 %d\n", res)
// 記憶化搜尋
mem := make([][]int, n)
@ -31,13 +31,13 @@ func TestMinPathSum(t *testing.T) {
}
}
res = minPathSumDFSMem(grid, mem, n-1, m-1)
fmt.Printf("從左上角到右下角的小路徑和為 %d\n", res)
fmt.Printf("從左上角到右下角的小路徑和為 %d\n", res)
// 動態規劃
res = minPathSumDP(grid)
fmt.Printf("從左上角到右下角的小路徑和為 %d\n", res)
fmt.Printf("從左上角到右下角的小路徑和為 %d\n", res)
// 空間最佳化後的動態規劃
res = minPathSumDPComp(grid)
fmt.Printf("從左上角到右下角的小路徑和為 %d\n", res)
fmt.Printf("從左上角到右下角的小路徑和為 %d\n", res)
}

View File

@ -88,17 +88,17 @@ if __name__ == "__main__":
# 暴力搜尋
res = min_path_sum_dfs(grid, n - 1, m - 1)
print(f"從左上角到右下角的小路徑和為 {res}")
print(f"從左上角到右下角的小路徑和為 {res}")
# 記憶化搜尋
mem = [[-1] * m for _ in range(n)]
res = min_path_sum_dfs_mem(grid, mem, n - 1, m - 1)
print(f"從左上角到右下角的小路徑和為 {res}")
print(f"從左上角到右下角的小路徑和為 {res}")
# 動態規劃
res = min_path_sum_dp(grid)
print(f"從左上角到右下角的小路徑和為 {res}")
print(f"從左上角到右下角的小路徑和為 {res}")
# 空間最佳化後的動態規劃
res = min_path_sum_dp_comp(grid)
print(f"從左上角到右下角的小路徑和為 {res}")
print(f"從左上角到右下角的小路徑和為 {res}")

View File

@ -76,18 +76,18 @@ if __FILE__ == $0
# 暴力搜尋
res = min_path_sum_dfs(grid, n - 1, m - 1)
puts "從左上角到右下角的小路徑和為 #{res}"
puts "從左上角到右下角的小路徑和為 #{res}"
# 記憶化搜尋
mem = Array.new(n) { Array.new(m, - 1) }
res = min_path_sum_dfs_mem(grid, mem, n - 1, m -1)
puts "從左上角到右下角的小路徑和為 #{res}"
puts "從左上角到右下角的小路徑和為 #{res}"
# 動態規劃
res = min_path_sum_dp(grid)
puts "從左上角到右下角的小路徑和為 #{res}"
puts "從左上角到右下角的小路徑和為 #{res}"
# 空間最佳化後的動態規劃
res = min_path_sum_dp_comp(grid)
puts "從左上角到右下角的小路徑和為 #{res}"
puts "從左上角到右下角的小路徑和為 #{res}"
end

View File

@ -4,8 +4,7 @@
* Author: xBLACICEx (xBLACKICEx@outlook.com), codingonion (coderonion@gmail.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::print_util;
use rand::Rng;
/* 隨機訪問元素 */

View File

@ -4,9 +4,7 @@
* Author: codingonion (coderonion@gmail.com)
*/
include!("../include/include.rs");
use list_node::ListNode;
use hello_algo_rust::include::{print_util, ListNode};
use std::cell::RefCell;
use std::rc::Rc;

View File

@ -3,8 +3,7 @@
* Created Time: 2023-01-18
* Author: xBLACICEx (xBLACKICEx@outlook.com), codingonion (coderonion@gmail.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::print_util;
/* Driver Code */
fn main() {

View File

@ -4,7 +4,7 @@
* Author: codingonion (coderonion@gmail.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::print_util;
/* 串列類別 */
#[allow(dead_code)]

View File

@ -4,10 +4,8 @@
* Author: codingonion (coderonion@gmail.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::{print_util, vec_to_tree, TreeNode};
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>>>) {

View File

@ -4,10 +4,8 @@
* Author: codingonion (coderonion@gmail.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::{print_util, vec_to_tree, TreeNode};
use std::{cell::RefCell, rc::Rc};
use tree_node::{vec_to_tree, TreeNode};
/* 前序走訪:例題二 */
fn pre_order(

View File

@ -4,10 +4,8 @@
* Author: codingonion (coderonion@gmail.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::{print_util, vec_to_tree, TreeNode};
use std::{cell::RefCell, rc::Rc};
use tree_node::{vec_to_tree, TreeNode};
/* 前序走訪:例題三 */
fn pre_order(

View File

@ -4,10 +4,8 @@
* Author: codingonion (coderonion@gmail.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::{print_util, vec_to_tree, TreeNode};
use std::{cell::RefCell, rc::Rc};
use tree_node::{vec_to_tree, TreeNode};
/* 判斷當前狀態是否為解 */
fn is_solution(state: &mut Vec<Rc<RefCell<TreeNode>>>) -> bool {

View File

@ -4,13 +4,10 @@
* Author: codingonion (coderonion@gmail.com)
*/
include!("../include/include.rs");
use list_node::ListNode;
use hello_algo_rust::include::{print_util, ListNode, TreeNode};
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use tree_node::TreeNode;
/* 函式 */
fn function() -> i32 {

View File

@ -4,8 +4,7 @@
* Author: xBLACICEx (xBLACKICEx@outlook.com), codingonion (coderonion@gmail.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::print_util;
use rand::seq::SliceRandom;
use rand::thread_rng;

View File

@ -4,10 +4,9 @@
* Author: codingonion (coderonion@gmail.com)
*/
use hello_algo_rust::include::{print_util, TreeNode};
use std::collections::HashMap;
use std::{cell::RefCell, rc::Rc};
include!("../include/include.rs");
use tree_node::TreeNode;
/* 構建二元樹:分治 */
fn dfs(

View File

@ -4,7 +4,7 @@
* Author: night-cruise (2586447362@qq.com)
*/
include!("../include/vertex.rs");
pub use hello_algo_rust::include::{vals_to_vets, vets_to_vals, Vertex};
use std::collections::HashMap;

View File

@ -4,9 +4,8 @@
* Author: WSL0809 (wslzzy@outlook.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::ListNode;
use crate::list_node::ListNode;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

View File

@ -4,7 +4,7 @@
* Author: codingonion (coderonion@gmail.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::print_util;
use std::collections::HashMap;

View File

@ -4,7 +4,7 @@
* Author: night-cruise (2586447362@qq.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::print_util;
use std::collections::BinaryHeap;

View File

@ -4,7 +4,7 @@
* Author: night-cruise (2586447362@qq.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::print_util;
/* 大頂堆積 */
struct MaxHeap {

View File

@ -4,7 +4,7 @@
* Author: night-cruise (2586447362@qq.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::print_util;
use std::cmp::Reverse;
use std::collections::BinaryHeap;

View File

@ -4,9 +4,7 @@
* Author: codingonion (coderonion@gmail.com)
*/
include!("../include/include.rs");
use list_node::ListNode;
use hello_algo_rust::include::ListNode;
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;

View File

@ -4,9 +4,7 @@
* Author: codingonion (coderonion@gmail.com)
*/
include!("../include/include.rs");
use list_node::ListNode;
use hello_algo_rust::include::ListNode;
use std::cell::RefCell;
use std::rc::Rc;

View File

@ -4,8 +4,7 @@
* Author: xBLACICEx (xBLACKICEx@outlook.com), codingonion (coderonion@gmail.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::print_util;
use std::collections::HashMap;
/* 方法一:暴力列舉 */

View File

@ -4,7 +4,7 @@
* Author: codingonion (coderonion@gmail.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::print_util;
/* 泡沫排序 */
fn bubble_sort(nums: &mut [i32]) {

View File

@ -4,7 +4,7 @@
* Author: night-cruise (2586447362@qq.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::print_util;
/* 桶排序 */
fn bucket_sort(nums: &mut [f64]) {

View File

@ -4,7 +4,7 @@
* Author: night-cruise (2586447362@qq.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::print_util;
/* 計數排序 */
// 簡單實現,無法用於排序物件

View File

@ -4,7 +4,7 @@
* Author: night-cruise (2586447362@qq.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::print_util;
/* 堆積的長度為 n ,從節點 i 開始,從頂至底堆積化 */
fn sift_down(nums: &mut [i32], n: usize, mut i: usize) {

View File

@ -4,7 +4,7 @@
* Author: xBLACKICEx (xBLACKICEx@outlook.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::print_util;
/* 插入排序 */
fn insertion_sort(nums: &mut [i32]) {

View File

@ -4,7 +4,7 @@
* Author: night-cruise (2586447362@qq.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::print_util;
/* 獲取元素 num 的第 k 位,其中 exp = 10^(k-1) */
fn digit(num: i32, exp: i32) -> usize {

View File

@ -4,7 +4,7 @@
* Author: WSL0809 (wslzzy@outlook.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::print_util;
/* 選擇排序 */
fn selection_sort(nums: &mut [i32]) {

View File

@ -3,9 +3,7 @@
* Created Time: 2023-03-11
* Author: codingonion (coderonion@gmail.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::print_util;
/* 基於環形陣列實現的雙向佇列 */
struct ArrayDeque {
nums: Vec<i32>, // 用於儲存雙向佇列元素的陣列

View File

@ -4,7 +4,7 @@
* Author: WSL0809 (wslzzy@outlook.com), codingonion (coderonion@gmail.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::print_util;
/* 基於陣列實現的堆疊 */
struct ArrayStack<T> {

View File

@ -4,8 +4,7 @@
* Author: codingonion (coderonion@gmail.com), xBLACKICEx (xBLACKICEx@outlook.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::print_util;
use std::collections::VecDeque;
/* Driver Code */

View File

@ -4,7 +4,7 @@
* Author: codingonion (coderonion@gmail.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::print_util;
use std::cell::RefCell;
use std::rc::Rc;

View File

@ -4,9 +4,8 @@
* Author: codingonion (coderonion@gmail.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::{print_util, ListNode};
use list_node::ListNode;
use std::cell::RefCell;
use std::rc::Rc;

View File

@ -4,9 +4,8 @@
* Author: codingonion (coderonion@gmail.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::{print_util, ListNode};
use list_node::ListNode;
use std::cell::RefCell;
use std::rc::Rc;

View File

@ -4,7 +4,7 @@
* Author: codingonion (coderonion@gmail.com), xBLACKICEx (xBLACKICEx@outlook.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::print_util;
use std::collections::VecDeque;

View File

@ -4,7 +4,7 @@
* Author: codingonion (coderonion@gmail.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::print_util;
/* Driver Code */
pub fn main() {

View File

@ -4,7 +4,7 @@
* Author: night-cruise (2586447362@qq.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::{print_util, tree_node};
/* 陣列表示下的二元樹類別 */
struct ArrayBinaryTree {
@ -49,18 +49,11 @@ impl ArrayBinaryTree {
/* 層序走訪 */
fn level_order(&self) -> Vec<i32> {
let mut res = vec![];
// 直接走訪陣列
for i in 0..self.size() {
if let Some(val) = self.val(i) {
res.push(val)
}
}
res
self.tree.iter().filter_map(|&x| x).collect()
}
/* 深度優先走訪 */
fn dfs(&self, i: i32, order: &str, res: &mut Vec<i32>) {
fn dfs(&self, i: i32, order: &'static str, res: &mut Vec<i32>) {
if self.val(i).is_none() {
return;
}

View File

@ -4,12 +4,11 @@
* Author: night-cruise (2586447362@qq.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::{print_util, TreeNode};
use std::cell::RefCell;
use std::cmp::Ordering;
use std::rc::Rc;
use tree_node::TreeNode;
type OptionTreeNodeRc = Option<Rc<RefCell<TreeNode>>>;

View File

@ -4,13 +4,13 @@
* Author: xBLACKICEx (xBLACKICE@outlook.com)night-cruise (2586447362@qq.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::print_util;
use std::cell::RefCell;
use std::cmp::Ordering;
use std::rc::Rc;
use tree_node::TreeNode;
use hello_algo_rust::include::TreeNode;
type OptionTreeNodeRc = Option<Rc<RefCell<TreeNode>>>;
@ -126,7 +126,7 @@ impl BinarySearchTree {
// 刪除節點 cur
if !Rc::ptr_eq(&cur, self.root.as_ref().unwrap()) {
let left = pre.borrow().left.clone();
if left.is_some() && Rc::ptr_eq(&left.as_ref().unwrap(), &cur) {
if left.is_some() && Rc::ptr_eq(left.as_ref().unwrap(), &cur) {
pre.borrow_mut().left = child;
} else {
pre.borrow_mut().right = child;
@ -147,11 +147,11 @@ impl BinarySearchTree {
break;
}
}
let tmpval = tmp.unwrap().borrow().val;
let tmp_val = tmp.unwrap().borrow().val;
// 遞迴刪除節點 tmp
self.remove(tmpval);
self.remove(tmp_val);
// 用 tmp 覆蓋 cur
cur.borrow_mut().val = tmpval;
cur.borrow_mut().val = tmp_val;
}
}
}

View File

@ -4,8 +4,7 @@
* Author: xBLACKICEx (xBLACKICE@outlook.com)
*/
use std::rc::Rc;
include!("../include/include.rs");
use tree_node::TreeNode;
use hello_algo_rust::include::{print_util, TreeNode};
/* Driver Code */
fn main() {

View File

@ -4,11 +4,11 @@
* Author: xBLACKICEx (xBLACKICE@outlook.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::{print_util, vec_to_tree, TreeNode};
use hello_algo_rust::op_vec;
use std::collections::VecDeque;
use std::{cell::RefCell, rc::Rc};
use tree_node::{vec_to_tree, TreeNode};
/* 層序走訪 */
fn level_order(root: &Rc<RefCell<TreeNode>>) -> Vec<i32> {

View File

@ -4,22 +4,27 @@
* Author: xBLACKICEx (xBLACKICE@outlook.com)
*/
include!("../include/include.rs");
use hello_algo_rust::include::{print_util, vec_to_tree, TreeNode};
use hello_algo_rust::op_vec;
use std::cell::RefCell;
use std::rc::Rc;
use tree_node::{vec_to_tree, TreeNode};
/* 前序走訪 */
fn pre_order(root: Option<&Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut result = vec![];
if let Some(node) = root {
// 訪問優先順序:根節點 -> 左子樹 -> 右子樹
result.push(node.borrow().val);
result.extend(pre_order(node.borrow().left.as_ref()));
result.extend(pre_order(node.borrow().right.as_ref()));
fn dfs(root: Option<&Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) {
if let Some(node) = root {
// 訪問優先順序:根節點 -> 左子樹 -> 右子樹
let node = node.borrow();
res.push(node.val);
dfs(node.left.as_ref(), res);
dfs(node.right.as_ref(), res);
}
}
dfs(root, &mut result);
result
}
@ -27,12 +32,17 @@ fn pre_order(root: Option<&Rc<RefCell<TreeNode>>>) -> Vec<i32> {
fn in_order(root: Option<&Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut result = vec![];
if let Some(node) = root {
// 訪問優先順序:左子樹 -> 根節點 -> 右子樹
result.extend(in_order(node.borrow().left.as_ref()));
result.push(node.borrow().val);
result.extend(in_order(node.borrow().right.as_ref()));
fn dfs(root: Option<&Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) {
if let Some(node) = root {
// 訪問優先順序:左子樹 -> 根節點 -> 右子樹
let node = node.borrow();
dfs(node.left.as_ref(), res);
res.push(node.val);
dfs(node.right.as_ref(), res);
}
}
dfs(root, &mut result);
result
}
@ -40,12 +50,18 @@ fn in_order(root: Option<&Rc<RefCell<TreeNode>>>) -> Vec<i32> {
fn post_order(root: Option<&Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut result = vec![];
if let Some(node) = root {
// 訪問優先順序:左子樹 -> 右子樹 -> 根節點
result.extend(post_order(node.borrow().left.as_ref()));
result.extend(post_order(node.borrow().right.as_ref()));
result.push(node.borrow().val);
fn dfs(root: Option<&Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) {
if let Some(node) = root {
// 訪問優先順序:左子樹 -> 右子樹 -> 根節點
let node = node.borrow();
dfs(node.left.as_ref(), res);
dfs(node.right.as_ref(), res);
res.push(node.val);
}
}
dfs(root, &mut result);
result
}

View File

@ -0,0 +1,57 @@
/*
* File: list_node.rs
* Created Time: 2023-03-05
* Author: codingonion (coderonion@gmail.com), rongyi (hiarongyi@gmail.com)
*/
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
#[derive(Debug)]
pub struct ListNode<T> {
pub val: T,
pub next: Option<Rc<RefCell<ListNode<T>>>>,
}
impl<T> ListNode<T> {
pub fn new(val: T) -> Rc<RefCell<ListNode<T>>> {
Rc::new(RefCell::new(ListNode { val, next: None }))
}
/* 將陣列反序列化為鏈結串列 */
pub fn arr_to_linked_list(array: &[T]) -> Option<Rc<RefCell<ListNode<T>>>>
where
T: Copy + Clone,
{
let mut head = None;
// insert in reverse order
for item in array.iter().rev() {
let node = Rc::new(RefCell::new(ListNode {
val: *item,
next: head.take(),
}));
head = Some(node);
}
head
}
/* 將鏈結串列轉化為雜湊表 */
pub fn linked_list_to_hashmap(
linked_list: Option<Rc<RefCell<ListNode<T>>>>,
) -> HashMap<T, Rc<RefCell<ListNode<T>>>>
where
T: std::hash::Hash + Eq + Copy + Clone,
{
let mut hashmap = HashMap::new();
let mut node = linked_list;
while let Some(cur) = node {
let borrow = cur.borrow();
hashmap.insert(borrow.val.clone(), cur.clone());
node = borrow.next.clone();
}
hashmap
}
}

View File

@ -0,0 +1,16 @@
/*
* File: include.rs
* Created Time: 2023-02-05
* Author: codingonion (coderonion@gmail.com), xBLACKICEx (xBLACKICE@outlook.com)
*/
pub mod list_node;
pub mod print_util;
pub mod tree_node;
pub mod vertex;
// rexport to include
pub use list_node::*;
pub use print_util::*;
pub use tree_node::*;
pub use vertex::*;

View File

@ -0,0 +1,103 @@
/*
* File: print_util.rs
* Created Time: 2023-02-05
* Author: codingonion (coderonion@gmail.com), xBLACKICEx (xBLACKICEx@outlook.com)
*/
use std::cell::{Cell, RefCell};
use std::fmt::Display;
use std::collections::{HashMap, VecDeque};
use std::rc::Rc;
use super::list_node::ListNode;
use super::tree_node::{TreeNode, vec_to_tree};
struct Trunk<'a, 'b> {
prev: Option<&'a Trunk<'a, 'b>>,
str: Cell<&'b str>,
}
/* 列印陣列 */
pub fn print_array<T: Display>(nums: &[T]) {
print!("[");
if nums.len() > 0 {
for (i, num) in nums.iter().enumerate() {
print!("{}{}", num, if i == nums.len() - 1 {"]"} else {", "} );
}
} else {
print!("]");
}
}
/* 列印雜湊表 */
pub fn print_hash_map<TKey: Display, TValue: Display>(map: &HashMap<TKey, TValue>) {
for (key, value) in map {
println!("{key} -> {value}");
}
}
/* 列印佇列(雙向佇列) */
pub fn print_queue<T: Display>(queue: &VecDeque<T>) {
print!("[");
let iter = queue.iter();
for (i, data) in iter.enumerate() {
print!("{}{}", data, if i == queue.len() - 1 {"]"} else {", "} );
}
}
/* 列印鏈結串列 */
pub fn print_linked_list<T: Display>(head: &Rc<RefCell<ListNode<T>>>) {
print!("{}{}", head.borrow().val, if head.borrow().next.is_none() {"\n"} else {" -> "});
if let Some(node) = &head.borrow().next {
return print_linked_list(node);
}
}
/* 列印二元樹 */
pub fn print_tree(root: &Rc<RefCell<TreeNode>>) {
_print_tree(Some(root), None, false);
}
/* 列印二元樹 */
fn _print_tree(root: Option<&Rc<RefCell<TreeNode>>>, prev: Option<&Trunk>, is_right: bool) {
if let Some(node) = root {
let mut prev_str = " ";
let trunk = Trunk { prev, str: Cell::new(prev_str) };
_print_tree(node.borrow().right.as_ref(), Some(&trunk), true);
if prev.is_none() {
trunk.str.set("———");
} else if is_right {
trunk.str.set("/———");
prev_str = " |";
} else {
trunk.str.set("\\———");
prev.as_ref().unwrap().str.set(prev_str);
}
show_trunks(Some(&trunk));
println!(" {}", node.borrow().val);
if let Some(prev) = prev {
prev.str.set(prev_str);
}
trunk.str.set(" |");
_print_tree(node.borrow().left.as_ref(), Some(&trunk), false);
}
}
fn show_trunks(trunk: Option<&Trunk>) {
if let Some(trunk) = trunk {
show_trunks(trunk.prev);
print!("{}", trunk.str.get());
}
}
/* 列印堆積 */
pub fn print_heap(heap: Vec<i32>) {
println!("堆積的陣列表示:{:?}", heap);
println!("堆積的樹狀表示:");
if let Some(root) = vec_to_tree(heap.into_iter().map(|val| Some(val)).collect()) {
print_tree(&root);
}
}

View File

@ -0,0 +1,92 @@
/*
* File: tree_node.rs
* Created Time: 2023-02-27
* Author: xBLACKICEx (xBLACKICE@outlook.com), night-cruise (2586447362@qq.com)
*/
use std::cell::RefCell;
use std::rc::Rc;
/* 二元樹節點型別 */
#[derive(Debug)]
pub struct TreeNode {
pub val: i32,
pub height: i32,
pub parent: Option<Rc<RefCell<TreeNode>>>,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
/* 建構子 */
pub fn new(val: i32) -> Rc<RefCell<Self>> {
Rc::new(RefCell::new(Self {
val,
height: 0,
parent: None,
left: None,
right: None,
}))
}
}
#[macro_export]
macro_rules! op_vec {
( $( $x:expr ),* ) => {
vec![
$( Option::from($x).map(|x| x) ),*
]
};
}
// 序列化編碼規則請參考:
// https://www.hello-algo.com/chapter_tree/array_representation_of_tree/
// 二元樹的陣列表示:
// [1, 2, 3, 4, None, 6, 7, 8, 9, None, None, 12, None, None, 15]
// 二元樹的鏈結串列表示:
// /——— 15
// /——— 7
// /——— 3
// | \——— 6
// | \——— 12
// ——— 1
// \——— 2
// | /——— 9
// \——— 4
// \——— 8
/* 將串列反序列化為二元樹:遞迴 */
fn vec_to_tree_dfs(arr: &[Option<i32>], i: usize) -> Option<Rc<RefCell<TreeNode>>> {
if i >= arr.len() || arr[i].is_none() {
return None;
}
let root = TreeNode::new(arr[i].unwrap());
root.borrow_mut().left = vec_to_tree_dfs(arr, 2 * i + 1);
root.borrow_mut().right = vec_to_tree_dfs(arr, 2 * i + 2);
Some(root)
}
/* 將串列反序列化為二元樹 */
pub fn vec_to_tree(arr: Vec<Option<i32>>) -> Option<Rc<RefCell<TreeNode>>> {
vec_to_tree_dfs(&arr, 0)
}
/* 將二元樹序列化為串列:遞迴 */
fn tree_to_vec_dfs(root: Option<&Rc<RefCell<TreeNode>>>, i: usize, res: &mut Vec<Option<i32>>) {
if let Some(root) = root {
// i + 1 is the minimum valid size to access index i
while res.len() < i + 1 {
res.push(None);
}
res[i] = Some(root.borrow().val);
tree_to_vec_dfs(root.borrow().left.as_ref(), 2 * i + 1, res);
tree_to_vec_dfs(root.borrow().right.as_ref(), 2 * i + 2, res);
}
}
/* 將二元樹序列化為串列 */
pub fn tree_to_vec(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Option<i32>> {
let mut res = vec![];
tree_to_vec_dfs(root.as_ref(), 0, &mut res);
res
}

View File

@ -0,0 +1,21 @@
/*
* File: vertex.rs
* Created Time: 2023-07-13
* Author: night-cruise (2586447362@qq.com)
*/
/* 頂點型別 */
#[derive(Copy, Clone, Hash, PartialEq, Eq)]
pub struct Vertex {
pub val: i32,
}
/* 輸入值串列 vals ,返回頂點串列 vets */
pub fn vals_to_vets(vals: Vec<i32>) -> Vec<Vertex> {
vals.into_iter().map(|val| Vertex { val }).collect()
}
/* 輸入頂點串列 vets ,返回值串列 vals */
pub fn vets_to_vals(vets: Vec<Vertex>) -> Vec<i32> {
vets.into_iter().map(|vet| vet.val).collect()
}

View File

@ -0,0 +1 @@
pub mod include;

View File

@ -105,19 +105,19 @@ enum MinPathSum {
//
var res = minPathSumDFS(grid: grid, i: n - 1, j: m - 1)
print("從左上角到右下角的小路徑和為 \(res)")
print("從左上角到右下角的小路徑和為 \(res)")
//
var mem = Array(repeating: Array(repeating: -1, count: m), count: n)
res = minPathSumDFSMem(grid: grid, mem: &mem, i: n - 1, j: m - 1)
print("從左上角到右下角的小路徑和為 \(res)")
print("從左上角到右下角的小路徑和為 \(res)")
//
res = minPathSumDP(grid: grid)
print("從左上角到右下角的小路徑和為 \(res)")
print("從左上角到右下角的小路徑和為 \(res)")
//
res = minPathSumDPComp(grid: grid)
print("從左上角到右下角的小路徑和為 \(res)")
print("從左上角到右下角的小路徑和為 \(res)")
}
}

View File

@ -157,8 +157,8 @@
/* 初始化堆積 */
// 初始化小頂堆積
PriorityQueue<int, int> minHeap = new();
// 初始化大頂堆積(使用 lambda 表示式修改 Comparator 即可)
PriorityQueue<int, int> maxHeap = new(Comparer<int>.Create((x, y) => y - x));
// 初始化大頂堆積(使用 lambda 表示式修改 Comparer 即可)
PriorityQueue<int, int> maxHeap = new(Comparer<int>.Create((x, y) => y.CompareTo(x)));
/* 元素入堆積 */
maxHeap.Enqueue(1, 1);

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 13 KiB

View File

@ -180,7 +180,7 @@ AVL 樹既是二元搜尋樹,也是平衡二元樹,同時滿足這兩類二
```c title=""
/* AVL 樹節點結構體 */
TreeNode struct TreeNode {
typedef struct TreeNode {
int val;
int height;
struct TreeNode *left;

View File

@ -372,4 +372,4 @@
</a>
</div>
</div>
</section>
</section>