mirror of
https://github.com/krahets/hello-algo.git
synced 2026-08-29 11:27:13 +00:00
feat: Traditional Chinese version (#1163)
* First commit * Update mkdocs.yml * Translate all the docs to traditional Chinese * Translate the code files. * Translate the docker file * Fix mkdocs.yml * Translate all the figures from SC to TC * 二叉搜尋樹 -> 二元搜尋樹 * Update terminology. * Update terminology * 构造函数/构造方法 -> 建構子 异或 -> 互斥或 * 擴充套件 -> 擴展 * constant - 常量 - 常數 * 類 -> 類別 * AVL -> AVL 樹 * 數組 -> 陣列 * 係統 -> 系統 斐波那契數列 -> 費波那契數列 運算元量 -> 運算量 引數 -> 參數 * 聯絡 -> 關聯 * 麵試 -> 面試 * 面向物件 -> 物件導向 歸併排序 -> 合併排序 范式 -> 範式 * Fix 算法 -> 演算法 * 錶示 -> 表示 反碼 -> 一補數 補碼 -> 二補數 列列尾部 -> 佇列尾部 區域性性 -> 區域性 一摞 -> 一疊 * Synchronize with main branch * 賬號 -> 帳號 推匯 -> 推導 * Sync with main branch * First commit * Update mkdocs.yml * Translate all the docs to traditional Chinese * Translate the code files. * Translate the docker file * Fix mkdocs.yml * Translate all the figures from SC to TC * 二叉搜尋樹 -> 二元搜尋樹 * Update terminology * 构造函数/构造方法 -> 建構子 异或 -> 互斥或 * 擴充套件 -> 擴展 * constant - 常量 - 常數 * 類 -> 類別 * AVL -> AVL 樹 * 數組 -> 陣列 * 係統 -> 系統 斐波那契數列 -> 費波那契數列 運算元量 -> 運算量 引數 -> 參數 * 聯絡 -> 關聯 * 麵試 -> 面試 * 面向物件 -> 物件導向 歸併排序 -> 合併排序 范式 -> 範式 * Fix 算法 -> 演算法 * 錶示 -> 表示 反碼 -> 一補數 補碼 -> 二補數 列列尾部 -> 佇列尾部 區域性性 -> 區域性 一摞 -> 一疊 * Synchronize with main branch * 賬號 -> 帳號 推匯 -> 推導 * Sync with main branch * Update terminology.md * 操作数量(num. of operations)-> 操作數量 * 字首和->前綴和 * Update figures * 歸 -> 迴 記憶體洩漏 -> 記憶體流失 * Fix the bug of the file filter * 支援 -> 支持 Add zh-Hant/README.md * Add the zh-Hant chapter covers. Bug fixes. * 外掛 -> 擴充功能 * Add the landing page for zh-Hant version * Unify the font of the chapter covers for the zh, en, and zh-Hant version * Move zh-Hant/ to zh-hant/ * Translate terminology.md to traditional Chinese
This commit is contained in:
@@ -0,0 +1,88 @@
|
||||
# CSharp formatting rules
|
||||
[*.cs]
|
||||
csharp_new_line_before_open_brace = none
|
||||
csharp_new_line_before_else = false
|
||||
csharp_new_line_before_catch = false
|
||||
csharp_new_line_before_finally = false
|
||||
csharp_indent_labels = one_less_than_current
|
||||
csharp_using_directive_placement = outside_namespace:silent
|
||||
csharp_prefer_simple_using_statement = true:suggestion
|
||||
csharp_prefer_braces = true:silent
|
||||
csharp_style_namespace_declarations = block_scoped:silent
|
||||
csharp_style_prefer_method_group_conversion = true:silent
|
||||
csharp_style_prefer_top_level_statements = true:silent
|
||||
csharp_style_prefer_primary_constructors = true:suggestion
|
||||
csharp_style_expression_bodied_methods = false:silent
|
||||
csharp_style_expression_bodied_constructors = false:silent
|
||||
csharp_style_expression_bodied_operators = false:silent
|
||||
csharp_style_expression_bodied_properties = true:silent
|
||||
csharp_style_expression_bodied_indexers = true:silent
|
||||
csharp_style_expression_bodied_accessors = true:silent
|
||||
csharp_style_expression_bodied_lambdas = true:silent
|
||||
|
||||
# CS8981: The type name only contains lower-cased ascii characters. Such names may become reserved for the language.
|
||||
dotnet_diagnostic.CS8981.severity = silent
|
||||
|
||||
# IDE1006: Naming Styles
|
||||
dotnet_diagnostic.IDE1006.severity = silent
|
||||
|
||||
# CA1822: Mark members as static
|
||||
dotnet_diagnostic.CA1822.severity = silent
|
||||
|
||||
[*.{cs,vb}]
|
||||
#### Naming styles ####
|
||||
|
||||
# Naming rules
|
||||
|
||||
dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion
|
||||
dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface
|
||||
dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i
|
||||
|
||||
dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion
|
||||
dotnet_naming_rule.types_should_be_pascal_case.symbols = types
|
||||
dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case
|
||||
|
||||
dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion
|
||||
dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members
|
||||
dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case
|
||||
|
||||
# Symbol specifications
|
||||
|
||||
dotnet_naming_symbols.interface.applicable_kinds = interface
|
||||
dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
|
||||
dotnet_naming_symbols.interface.required_modifiers =
|
||||
|
||||
dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum
|
||||
dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
|
||||
dotnet_naming_symbols.types.required_modifiers =
|
||||
|
||||
dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
|
||||
dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
|
||||
dotnet_naming_symbols.non_field_members.required_modifiers =
|
||||
|
||||
# Naming styles
|
||||
|
||||
dotnet_naming_style.begins_with_i.required_prefix = I
|
||||
dotnet_naming_style.begins_with_i.required_suffix =
|
||||
dotnet_naming_style.begins_with_i.word_separator =
|
||||
dotnet_naming_style.begins_with_i.capitalization = pascal_case
|
||||
|
||||
dotnet_naming_style.pascal_case.required_prefix =
|
||||
dotnet_naming_style.pascal_case.required_suffix =
|
||||
dotnet_naming_style.pascal_case.word_separator =
|
||||
dotnet_naming_style.pascal_case.capitalization = pascal_case
|
||||
|
||||
dotnet_naming_style.pascal_case.required_prefix =
|
||||
dotnet_naming_style.pascal_case.required_suffix =
|
||||
dotnet_naming_style.pascal_case.word_separator =
|
||||
dotnet_naming_style.pascal_case.capitalization = pascal_case
|
||||
dotnet_style_operator_placement_when_wrapping = beginning_of_line
|
||||
tab_width = 4
|
||||
indent_size = 4
|
||||
end_of_line = crlf
|
||||
|
||||
# IDE0040: Add accessibility modifiers
|
||||
dotnet_diagnostic.IDE0040.severity = silent
|
||||
|
||||
# IDE0044: Add readonly modifier
|
||||
dotnet_diagnostic.IDE0044.severity = silent
|
||||
@@ -0,0 +1,5 @@
|
||||
.idea/
|
||||
.vs/
|
||||
obj/
|
||||
.Debug
|
||||
bin/
|
||||
@@ -0,0 +1,3 @@
|
||||
global using NUnit.Framework;
|
||||
global using hello_algo.utils;
|
||||
global using System.Text;
|
||||
@@ -0,0 +1,107 @@
|
||||
// File: array.cs
|
||||
// Created Time: 2022-12-14
|
||||
// Author: mingXta (1195669834@qq.com)
|
||||
|
||||
namespace hello_algo.chapter_array_and_linkedlist;
|
||||
|
||||
public class array {
|
||||
/* 隨機訪問元素 */
|
||||
int RandomAccess(int[] nums) {
|
||||
Random random = new();
|
||||
// 在區間 [0, nums.Length) 中隨機抽取一個數字
|
||||
int randomIndex = random.Next(nums.Length);
|
||||
// 獲取並返回隨機元素
|
||||
int randomNum = nums[randomIndex];
|
||||
return randomNum;
|
||||
}
|
||||
|
||||
/* 擴展陣列長度 */
|
||||
int[] Extend(int[] nums, int enlarge) {
|
||||
// 初始化一個擴展長度後的陣列
|
||||
int[] res = new int[nums.Length + enlarge];
|
||||
// 將原陣列中的所有元素複製到新陣列
|
||||
for (int i = 0; i < nums.Length; i++) {
|
||||
res[i] = nums[i];
|
||||
}
|
||||
// 返回擴展後的新陣列
|
||||
return res;
|
||||
}
|
||||
|
||||
/* 在陣列的索引 index 處插入元素 num */
|
||||
void Insert(int[] nums, int num, int index) {
|
||||
// 把索引 index 以及之後的所有元素向後移動一位
|
||||
for (int i = nums.Length - 1; i > index; i--) {
|
||||
nums[i] = nums[i - 1];
|
||||
}
|
||||
// 將 num 賦給 index 處的元素
|
||||
nums[index] = num;
|
||||
}
|
||||
|
||||
/* 刪除索引 index 處的元素 */
|
||||
void Remove(int[] nums, int index) {
|
||||
// 把索引 index 之後的所有元素向前移動一位
|
||||
for (int i = index; i < nums.Length - 1; i++) {
|
||||
nums[i] = nums[i + 1];
|
||||
}
|
||||
}
|
||||
|
||||
/* 走訪陣列 */
|
||||
void Traverse(int[] nums) {
|
||||
int count = 0;
|
||||
// 透過索引走訪陣列
|
||||
for (int i = 0; i < nums.Length; i++) {
|
||||
count += nums[i];
|
||||
}
|
||||
// 直接走訪陣列元素
|
||||
foreach (int num in nums) {
|
||||
count += num;
|
||||
}
|
||||
}
|
||||
|
||||
/* 在陣列中查詢指定元素 */
|
||||
int Find(int[] nums, int target) {
|
||||
for (int i = 0; i < nums.Length; i++) {
|
||||
if (nums[i] == target)
|
||||
return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* 輔助函式,陣列轉字串 */
|
||||
string ToString(int[] nums) {
|
||||
return string.Join(",", nums);
|
||||
}
|
||||
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
// 初始化陣列
|
||||
int[] arr = new int[5];
|
||||
Console.WriteLine("陣列 arr = " + ToString(arr));
|
||||
int[] nums = [1, 3, 2, 5, 4];
|
||||
Console.WriteLine("陣列 nums = " + ToString(nums));
|
||||
|
||||
// 隨機訪問
|
||||
int randomNum = RandomAccess(nums);
|
||||
Console.WriteLine("在 nums 中獲取隨機元素 " + randomNum);
|
||||
|
||||
// 長度擴展
|
||||
nums = Extend(nums, 3);
|
||||
Console.WriteLine("將陣列長度擴展至 8 ,得到 nums = " + ToString(nums));
|
||||
|
||||
// 插入元素
|
||||
Insert(nums, 6, 3);
|
||||
Console.WriteLine("在索引 3 處插入數字 6 ,得到 nums = " + ToString(nums));
|
||||
|
||||
// 刪除元素
|
||||
Remove(nums, 2);
|
||||
Console.WriteLine("刪除索引 2 處的元素,得到 nums = " + ToString(nums));
|
||||
|
||||
// 走訪陣列
|
||||
Traverse(nums);
|
||||
|
||||
// 查詢元素
|
||||
int index = Find(nums, 3);
|
||||
Console.WriteLine("在 nums 中查詢元素 3 ,得到索引 = " + index);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
// File: linked_list.cs
|
||||
// Created Time: 2022-12-16
|
||||
// Author: mingXta (1195669834@qq.com)
|
||||
|
||||
namespace hello_algo.chapter_array_and_linkedlist;
|
||||
|
||||
public class linked_list {
|
||||
/* 在鏈結串列的節點 n0 之後插入節點 P */
|
||||
void Insert(ListNode n0, ListNode P) {
|
||||
ListNode? n1 = n0.next;
|
||||
P.next = n1;
|
||||
n0.next = P;
|
||||
}
|
||||
|
||||
/* 刪除鏈結串列的節點 n0 之後的首個節點 */
|
||||
void Remove(ListNode n0) {
|
||||
if (n0.next == null)
|
||||
return;
|
||||
// n0 -> P -> n1
|
||||
ListNode P = n0.next;
|
||||
ListNode? n1 = P.next;
|
||||
n0.next = n1;
|
||||
}
|
||||
|
||||
/* 訪問鏈結串列中索引為 index 的節點 */
|
||||
ListNode? Access(ListNode? head, int index) {
|
||||
for (int i = 0; i < index; i++) {
|
||||
if (head == null)
|
||||
return null;
|
||||
head = head.next;
|
||||
}
|
||||
return head;
|
||||
}
|
||||
|
||||
/* 在鏈結串列中查詢值為 target 的首個節點 */
|
||||
int Find(ListNode? head, int target) {
|
||||
int index = 0;
|
||||
while (head != null) {
|
||||
if (head.val == target)
|
||||
return index;
|
||||
head = head.next;
|
||||
index++;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
// 初始化鏈結串列
|
||||
// 初始化各個節點
|
||||
ListNode n0 = new(1);
|
||||
ListNode n1 = new(3);
|
||||
ListNode n2 = new(2);
|
||||
ListNode n3 = new(5);
|
||||
ListNode n4 = new(4);
|
||||
// 構建節點之間的引用
|
||||
n0.next = n1;
|
||||
n1.next = n2;
|
||||
n2.next = n3;
|
||||
n3.next = n4;
|
||||
Console.WriteLine($"初始化的鏈結串列為{n0}");
|
||||
|
||||
// 插入節點
|
||||
Insert(n0, new ListNode(0));
|
||||
Console.WriteLine($"插入節點後的鏈結串列為{n0}");
|
||||
|
||||
// 刪除節點
|
||||
Remove(n0);
|
||||
Console.WriteLine($"刪除節點後的鏈結串列為{n0}");
|
||||
|
||||
// 訪問節點
|
||||
ListNode? node = Access(n0, 3);
|
||||
Console.WriteLine($"鏈結串列中索引 3 處的節點的值 = {node?.val}");
|
||||
|
||||
// 查詢節點
|
||||
int index = Find(n0, 2);
|
||||
Console.WriteLine($"鏈結串列中值為 2 的節點的索引 = {index}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* File: list.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_array_and_linkedlist;
|
||||
|
||||
public class list {
|
||||
[Test]
|
||||
public void Test() {
|
||||
|
||||
/* 初始化串列 */
|
||||
int[] numbers = [1, 3, 2, 5, 4];
|
||||
List<int> nums = [.. numbers];
|
||||
Console.WriteLine("串列 nums = " + string.Join(",", nums));
|
||||
|
||||
/* 訪問元素 */
|
||||
int num = nums[1];
|
||||
Console.WriteLine("訪問索引 1 處的元素,得到 num = " + num);
|
||||
|
||||
/* 更新元素 */
|
||||
nums[1] = 0;
|
||||
Console.WriteLine("將索引 1 處的元素更新為 0 ,得到 nums = " + string.Join(",", nums));
|
||||
|
||||
/* 清空串列 */
|
||||
nums.Clear();
|
||||
Console.WriteLine("清空串列後 nums = " + string.Join(",", nums));
|
||||
|
||||
/* 在尾部新增元素 */
|
||||
nums.Add(1);
|
||||
nums.Add(3);
|
||||
nums.Add(2);
|
||||
nums.Add(5);
|
||||
nums.Add(4);
|
||||
Console.WriteLine("新增元素後 nums = " + string.Join(",", nums));
|
||||
|
||||
/* 在中間插入元素 */
|
||||
nums.Insert(3, 6);
|
||||
Console.WriteLine("在索引 3 處插入數字 6 ,得到 nums = " + string.Join(",", nums));
|
||||
|
||||
/* 刪除元素 */
|
||||
nums.RemoveAt(3);
|
||||
Console.WriteLine("刪除索引 3 處的元素,得到 nums = " + string.Join(",", nums));
|
||||
|
||||
/* 透過索引走訪串列 */
|
||||
int count = 0;
|
||||
for (int i = 0; i < nums.Count; i++) {
|
||||
count += nums[i];
|
||||
}
|
||||
/* 直接走訪串列元素 */
|
||||
count = 0;
|
||||
foreach (int x in nums) {
|
||||
count += x;
|
||||
}
|
||||
|
||||
/* 拼接兩個串列 */
|
||||
List<int> nums1 = [6, 8, 7, 10, 9];
|
||||
nums.AddRange(nums1);
|
||||
Console.WriteLine("將串列 nums1 拼接到 nums 之後,得到 nums = " + string.Join(",", nums));
|
||||
|
||||
/* 排序串列 */
|
||||
nums.Sort(); // 排序後,串列元素從小到大排列
|
||||
Console.WriteLine("排序串列後 nums = " + string.Join(",", nums));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
/**
|
||||
* File: my_list.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_array_and_linkedlist;
|
||||
|
||||
/* 串列類別 */
|
||||
class MyList {
|
||||
private int[] arr; // 陣列(儲存串列元素)
|
||||
private int arrCapacity = 10; // 串列容量
|
||||
private int arrSize = 0; // 串列長度(當前元素數量)
|
||||
private readonly int extendRatio = 2; // 每次串列擴容的倍數
|
||||
|
||||
/* 建構子 */
|
||||
public MyList() {
|
||||
arr = new int[arrCapacity];
|
||||
}
|
||||
|
||||
/* 獲取串列長度(當前元素數量)*/
|
||||
public int Size() {
|
||||
return arrSize;
|
||||
}
|
||||
|
||||
/* 獲取串列容量 */
|
||||
public int Capacity() {
|
||||
return arrCapacity;
|
||||
}
|
||||
|
||||
/* 訪問元素 */
|
||||
public int Get(int index) {
|
||||
// 索引如果越界,則丟擲異常,下同
|
||||
if (index < 0 || index >= arrSize)
|
||||
throw new IndexOutOfRangeException("索引越界");
|
||||
return arr[index];
|
||||
}
|
||||
|
||||
/* 更新元素 */
|
||||
public void Set(int index, int num) {
|
||||
if (index < 0 || index >= arrSize)
|
||||
throw new IndexOutOfRangeException("索引越界");
|
||||
arr[index] = num;
|
||||
}
|
||||
|
||||
/* 在尾部新增元素 */
|
||||
public void Add(int num) {
|
||||
// 元素數量超出容量時,觸發擴容機制
|
||||
if (arrSize == arrCapacity)
|
||||
ExtendCapacity();
|
||||
arr[arrSize] = num;
|
||||
// 更新元素數量
|
||||
arrSize++;
|
||||
}
|
||||
|
||||
/* 在中間插入元素 */
|
||||
public void Insert(int index, int num) {
|
||||
if (index < 0 || index >= arrSize)
|
||||
throw new IndexOutOfRangeException("索引越界");
|
||||
// 元素數量超出容量時,觸發擴容機制
|
||||
if (arrSize == arrCapacity)
|
||||
ExtendCapacity();
|
||||
// 將索引 index 以及之後的元素都向後移動一位
|
||||
for (int j = arrSize - 1; j >= index; j--) {
|
||||
arr[j + 1] = arr[j];
|
||||
}
|
||||
arr[index] = num;
|
||||
// 更新元素數量
|
||||
arrSize++;
|
||||
}
|
||||
|
||||
/* 刪除元素 */
|
||||
public int Remove(int index) {
|
||||
if (index < 0 || index >= arrSize)
|
||||
throw new IndexOutOfRangeException("索引越界");
|
||||
int num = arr[index];
|
||||
// 將將索引 index 之後的元素都向前移動一位
|
||||
for (int j = index; j < arrSize - 1; j++) {
|
||||
arr[j] = arr[j + 1];
|
||||
}
|
||||
// 更新元素數量
|
||||
arrSize--;
|
||||
// 返回被刪除的元素
|
||||
return num;
|
||||
}
|
||||
|
||||
/* 串列擴容 */
|
||||
public void ExtendCapacity() {
|
||||
// 新建一個長度為 arrCapacity * extendRatio 的陣列,並將原陣列複製到新陣列
|
||||
Array.Resize(ref arr, arrCapacity * extendRatio);
|
||||
// 更新串列容量
|
||||
arrCapacity = arr.Length;
|
||||
}
|
||||
|
||||
/* 將串列轉換為陣列 */
|
||||
public int[] ToArray() {
|
||||
// 僅轉換有效長度範圍內的串列元素
|
||||
int[] arr = new int[arrSize];
|
||||
for (int i = 0; i < arrSize; i++) {
|
||||
arr[i] = Get(i);
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
}
|
||||
|
||||
public class my_list {
|
||||
[Test]
|
||||
public void Test() {
|
||||
/* 初始化串列 */
|
||||
MyList nums = new();
|
||||
/* 在尾部新增元素 */
|
||||
nums.Add(1);
|
||||
nums.Add(3);
|
||||
nums.Add(2);
|
||||
nums.Add(5);
|
||||
nums.Add(4);
|
||||
Console.WriteLine("串列 nums = " + string.Join(",", nums.ToArray()) +
|
||||
" ,容量 = " + nums.Capacity() + " ,長度 = " + nums.Size());
|
||||
|
||||
/* 在中間插入元素 */
|
||||
nums.Insert(3, 6);
|
||||
Console.WriteLine("在索引 3 處插入數字 6 ,得到 nums = " + string.Join(",", nums.ToArray()));
|
||||
|
||||
/* 刪除元素 */
|
||||
nums.Remove(3);
|
||||
Console.WriteLine("刪除索引 3 處的元素,得到 nums = " + string.Join(",", nums.ToArray()));
|
||||
|
||||
/* 訪問元素 */
|
||||
int num = nums.Get(1);
|
||||
Console.WriteLine("訪問索引 1 處的元素,得到 num = " + num);
|
||||
|
||||
/* 更新元素 */
|
||||
nums.Set(1, 0);
|
||||
Console.WriteLine("將索引 1 處的元素更新為 0 ,得到 nums = " + string.Join(",", nums.ToArray()));
|
||||
|
||||
/* 測試擴容機制 */
|
||||
for (int i = 0; i < 10; i++) {
|
||||
// 在 i = 5 時,串列長度將超出串列容量,此時觸發擴容機制
|
||||
nums.Add(i);
|
||||
}
|
||||
Console.WriteLine("擴容後的串列 nums = " + string.Join(",", nums.ToArray()) +
|
||||
" ,容量 = " + nums.Capacity() + " ,長度 = " + nums.Size());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* File: n_queens.cs
|
||||
* Created Time: 2023-05-04
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_backtracking;
|
||||
|
||||
public class n_queens {
|
||||
/* 回溯演算法:n 皇后 */
|
||||
void Backtrack(int row, int n, List<List<string>> state, List<List<List<string>>> res,
|
||||
bool[] cols, bool[] diags1, bool[] diags2) {
|
||||
// 當放置完所有行時,記錄解
|
||||
if (row == n) {
|
||||
List<List<string>> copyState = [];
|
||||
foreach (List<string> sRow in state) {
|
||||
copyState.Add(new List<string>(sRow));
|
||||
}
|
||||
res.Add(copyState);
|
||||
return;
|
||||
}
|
||||
// 走訪所有列
|
||||
for (int col = 0; col < n; col++) {
|
||||
// 計算該格子對應的主對角線和次對角線
|
||||
int diag1 = row - col + n - 1;
|
||||
int diag2 = row + col;
|
||||
// 剪枝:不允許該格子所在列、主對角線、次對角線上存在皇后
|
||||
if (!cols[col] && !diags1[diag1] && !diags2[diag2]) {
|
||||
// 嘗試:將皇后放置在該格子
|
||||
state[row][col] = "Q";
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = true;
|
||||
// 放置下一行
|
||||
Backtrack(row + 1, n, state, res, cols, diags1, diags2);
|
||||
// 回退:將該格子恢復為空位
|
||||
state[row][col] = "#";
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 求解 n 皇后 */
|
||||
List<List<List<string>>> NQueens(int n) {
|
||||
// 初始化 n*n 大小的棋盤,其中 'Q' 代表皇后,'#' 代表空位
|
||||
List<List<string>> state = [];
|
||||
for (int i = 0; i < n; i++) {
|
||||
List<string> row = [];
|
||||
for (int j = 0; j < n; j++) {
|
||||
row.Add("#");
|
||||
}
|
||||
state.Add(row);
|
||||
}
|
||||
bool[] cols = new bool[n]; // 記錄列是否有皇后
|
||||
bool[] diags1 = new bool[2 * n - 1]; // 記錄主對角線上是否有皇后
|
||||
bool[] diags2 = new bool[2 * n - 1]; // 記錄次對角線上是否有皇后
|
||||
List<List<List<string>>> res = [];
|
||||
|
||||
Backtrack(0, n, state, res, cols, diags1, diags2);
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int n = 4;
|
||||
List<List<List<string>>> res = NQueens(n);
|
||||
|
||||
Console.WriteLine("輸入棋盤長寬為 " + n);
|
||||
Console.WriteLine("皇后放置方案共有 " + res.Count + " 種");
|
||||
foreach (List<List<string>> state in res) {
|
||||
Console.WriteLine("--------------------");
|
||||
foreach (List<string> row in state) {
|
||||
PrintUtil.PrintList(row);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* File: permutations_i.cs
|
||||
* Created Time: 2023-04-24
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_backtracking;
|
||||
|
||||
public class permutations_i {
|
||||
/* 回溯演算法:全排列 I */
|
||||
void Backtrack(List<int> state, int[] choices, bool[] selected, List<List<int>> res) {
|
||||
// 當狀態長度等於元素數量時,記錄解
|
||||
if (state.Count == choices.Length) {
|
||||
res.Add(new List<int>(state));
|
||||
return;
|
||||
}
|
||||
// 走訪所有選擇
|
||||
for (int i = 0; i < choices.Length; i++) {
|
||||
int choice = choices[i];
|
||||
// 剪枝:不允許重複選擇元素
|
||||
if (!selected[i]) {
|
||||
// 嘗試:做出選擇,更新狀態
|
||||
selected[i] = true;
|
||||
state.Add(choice);
|
||||
// 進行下一輪選擇
|
||||
Backtrack(state, choices, selected, res);
|
||||
// 回退:撤銷選擇,恢復到之前的狀態
|
||||
selected[i] = false;
|
||||
state.RemoveAt(state.Count - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 全排列 I */
|
||||
List<List<int>> PermutationsI(int[] nums) {
|
||||
List<List<int>> res = [];
|
||||
Backtrack([], nums, new bool[nums.Length], res);
|
||||
return res;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int[] nums = [1, 2, 3];
|
||||
|
||||
List<List<int>> res = PermutationsI(nums);
|
||||
|
||||
Console.WriteLine("輸入陣列 nums = " + string.Join(", ", nums));
|
||||
Console.WriteLine("所有排列 res = ");
|
||||
foreach (List<int> permutation in res) {
|
||||
PrintUtil.PrintList(permutation);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* File: permutations_ii.cs
|
||||
* Created Time: 2023-04-24
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_backtracking;
|
||||
|
||||
public class permutations_ii {
|
||||
/* 回溯演算法:全排列 II */
|
||||
void Backtrack(List<int> state, int[] choices, bool[] selected, List<List<int>> res) {
|
||||
// 當狀態長度等於元素數量時,記錄解
|
||||
if (state.Count == choices.Length) {
|
||||
res.Add(new List<int>(state));
|
||||
return;
|
||||
}
|
||||
// 走訪所有選擇
|
||||
HashSet<int> duplicated = [];
|
||||
for (int i = 0; i < choices.Length; i++) {
|
||||
int choice = choices[i];
|
||||
// 剪枝:不允許重複選擇元素 且 不允許重複選擇相等元素
|
||||
if (!selected[i] && !duplicated.Contains(choice)) {
|
||||
// 嘗試:做出選擇,更新狀態
|
||||
duplicated.Add(choice); // 記錄選擇過的元素值
|
||||
selected[i] = true;
|
||||
state.Add(choice);
|
||||
// 進行下一輪選擇
|
||||
Backtrack(state, choices, selected, res);
|
||||
// 回退:撤銷選擇,恢復到之前的狀態
|
||||
selected[i] = false;
|
||||
state.RemoveAt(state.Count - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 全排列 II */
|
||||
List<List<int>> PermutationsII(int[] nums) {
|
||||
List<List<int>> res = [];
|
||||
Backtrack([], nums, new bool[nums.Length], res);
|
||||
return res;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int[] nums = [1, 2, 2];
|
||||
|
||||
List<List<int>> res = PermutationsII(nums);
|
||||
|
||||
Console.WriteLine("輸入陣列 nums = " + string.Join(", ", nums));
|
||||
Console.WriteLine("所有排列 res = ");
|
||||
foreach (List<int> permutation in res) {
|
||||
PrintUtil.PrintList(permutation);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* File: preorder_traversal_i_compact.cs
|
||||
* Created Time: 2023-04-17
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_backtracking;
|
||||
|
||||
public class preorder_traversal_i_compact {
|
||||
List<TreeNode> res = [];
|
||||
|
||||
/* 前序走訪:例題一 */
|
||||
void PreOrder(TreeNode? root) {
|
||||
if (root == null) {
|
||||
return;
|
||||
}
|
||||
if (root.val == 7) {
|
||||
// 記錄解
|
||||
res.Add(root);
|
||||
}
|
||||
PreOrder(root.left);
|
||||
PreOrder(root.right);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
TreeNode? root = TreeNode.ListToTree([1, 7, 3, 4, 5, 6, 7]);
|
||||
Console.WriteLine("\n初始化二元樹");
|
||||
PrintUtil.PrintTree(root);
|
||||
|
||||
// 前序走訪
|
||||
PreOrder(root);
|
||||
|
||||
Console.WriteLine("\n輸出所有值為 7 的節點");
|
||||
PrintUtil.PrintList(res.Select(p => p.val).ToList());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* File: preorder_traversal_ii_compact.cs
|
||||
* Created Time: 2023-04-17
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_backtracking;
|
||||
|
||||
public class preorder_traversal_ii_compact {
|
||||
List<TreeNode> path = [];
|
||||
List<List<TreeNode>> res = [];
|
||||
|
||||
/* 前序走訪:例題二 */
|
||||
void PreOrder(TreeNode? root) {
|
||||
if (root == null) {
|
||||
return;
|
||||
}
|
||||
// 嘗試
|
||||
path.Add(root);
|
||||
if (root.val == 7) {
|
||||
// 記錄解
|
||||
res.Add(new List<TreeNode>(path));
|
||||
}
|
||||
PreOrder(root.left);
|
||||
PreOrder(root.right);
|
||||
// 回退
|
||||
path.RemoveAt(path.Count - 1);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
TreeNode? root = TreeNode.ListToTree([1, 7, 3, 4, 5, 6, 7]);
|
||||
Console.WriteLine("\n初始化二元樹");
|
||||
PrintUtil.PrintTree(root);
|
||||
|
||||
// 前序走訪
|
||||
PreOrder(root);
|
||||
|
||||
Console.WriteLine("\n輸出所有根節點到節點 7 的路徑");
|
||||
foreach (List<TreeNode> path in res) {
|
||||
PrintUtil.PrintList(path.Select(p => p.val).ToList());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* File: preorder_traversal_iii_compact.cs
|
||||
* Created Time: 2023-04-17
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_backtracking;
|
||||
|
||||
public class preorder_traversal_iii_compact {
|
||||
List<TreeNode> path = [];
|
||||
List<List<TreeNode>> res = [];
|
||||
|
||||
/* 前序走訪:例題三 */
|
||||
void PreOrder(TreeNode? root) {
|
||||
// 剪枝
|
||||
if (root == null || root.val == 3) {
|
||||
return;
|
||||
}
|
||||
// 嘗試
|
||||
path.Add(root);
|
||||
if (root.val == 7) {
|
||||
// 記錄解
|
||||
res.Add(new List<TreeNode>(path));
|
||||
}
|
||||
PreOrder(root.left);
|
||||
PreOrder(root.right);
|
||||
// 回退
|
||||
path.RemoveAt(path.Count - 1);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
TreeNode? root = TreeNode.ListToTree([1, 7, 3, 4, 5, 6, 7]);
|
||||
Console.WriteLine("\n初始化二元樹");
|
||||
PrintUtil.PrintTree(root);
|
||||
|
||||
// 前序走訪
|
||||
PreOrder(root);
|
||||
|
||||
Console.WriteLine("\n輸出所有根節點到節點 7 的路徑,路徑中不包含值為 3 的節點");
|
||||
foreach (List<TreeNode> path in res) {
|
||||
PrintUtil.PrintList(path.Select(p => p.val).ToList());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* File: preorder_traversal_iii_template.cs
|
||||
* Created Time: 2023-04-17
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_backtracking;
|
||||
|
||||
public class preorder_traversal_iii_template {
|
||||
/* 判斷當前狀態是否為解 */
|
||||
bool IsSolution(List<TreeNode> state) {
|
||||
return state.Count != 0 && state[^1].val == 7;
|
||||
}
|
||||
|
||||
/* 記錄解 */
|
||||
void RecordSolution(List<TreeNode> state, List<List<TreeNode>> res) {
|
||||
res.Add(new List<TreeNode>(state));
|
||||
}
|
||||
|
||||
/* 判斷在當前狀態下,該選擇是否合法 */
|
||||
bool IsValid(List<TreeNode> state, TreeNode choice) {
|
||||
return choice != null && choice.val != 3;
|
||||
}
|
||||
|
||||
/* 更新狀態 */
|
||||
void MakeChoice(List<TreeNode> state, TreeNode choice) {
|
||||
state.Add(choice);
|
||||
}
|
||||
|
||||
/* 恢復狀態 */
|
||||
void UndoChoice(List<TreeNode> state, TreeNode choice) {
|
||||
state.RemoveAt(state.Count - 1);
|
||||
}
|
||||
|
||||
/* 回溯演算法:例題三 */
|
||||
void Backtrack(List<TreeNode> state, List<TreeNode> choices, List<List<TreeNode>> res) {
|
||||
// 檢查是否為解
|
||||
if (IsSolution(state)) {
|
||||
// 記錄解
|
||||
RecordSolution(state, res);
|
||||
}
|
||||
// 走訪所有選擇
|
||||
foreach (TreeNode choice in choices) {
|
||||
// 剪枝:檢查選擇是否合法
|
||||
if (IsValid(state, choice)) {
|
||||
// 嘗試:做出選擇,更新狀態
|
||||
MakeChoice(state, choice);
|
||||
// 進行下一輪選擇
|
||||
Backtrack(state, [choice.left!, choice.right!], res);
|
||||
// 回退:撤銷選擇,恢復到之前的狀態
|
||||
UndoChoice(state, choice);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
TreeNode? root = TreeNode.ListToTree([1, 7, 3, 4, 5, 6, 7]);
|
||||
Console.WriteLine("\n初始化二元樹");
|
||||
PrintUtil.PrintTree(root);
|
||||
|
||||
// 回溯演算法
|
||||
List<List<TreeNode>> res = [];
|
||||
List<TreeNode> choices = [root!];
|
||||
Backtrack([], choices, res);
|
||||
|
||||
Console.WriteLine("\n輸出所有根節點到節點 7 的路徑,要求路徑中不包含值為 3 的節點");
|
||||
foreach (List<TreeNode> path in res) {
|
||||
PrintUtil.PrintList(path.Select(p => p.val).ToList());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* File: subset_sum_i.cs
|
||||
* Created Time: 2023-06-25
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_backtracking;
|
||||
|
||||
public class subset_sum_i {
|
||||
/* 回溯演算法:子集和 I */
|
||||
void Backtrack(List<int> state, int target, int[] choices, int start, List<List<int>> res) {
|
||||
// 子集和等於 target 時,記錄解
|
||||
if (target == 0) {
|
||||
res.Add(new List<int>(state));
|
||||
return;
|
||||
}
|
||||
// 走訪所有選擇
|
||||
// 剪枝二:從 start 開始走訪,避免生成重複子集
|
||||
for (int i = start; i < choices.Length; i++) {
|
||||
// 剪枝一:若子集和超過 target ,則直接結束迴圈
|
||||
// 這是因為陣列已排序,後邊元素更大,子集和一定超過 target
|
||||
if (target - choices[i] < 0) {
|
||||
break;
|
||||
}
|
||||
// 嘗試:做出選擇,更新 target, start
|
||||
state.Add(choices[i]);
|
||||
// 進行下一輪選擇
|
||||
Backtrack(state, target - choices[i], choices, i, res);
|
||||
// 回退:撤銷選擇,恢復到之前的狀態
|
||||
state.RemoveAt(state.Count - 1);
|
||||
}
|
||||
}
|
||||
|
||||
/* 求解子集和 I */
|
||||
List<List<int>> SubsetSumI(int[] nums, int target) {
|
||||
List<int> state = []; // 狀態(子集)
|
||||
Array.Sort(nums); // 對 nums 進行排序
|
||||
int start = 0; // 走訪起始點
|
||||
List<List<int>> res = []; // 結果串列(子集串列)
|
||||
Backtrack(state, target, nums, start, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int[] nums = [3, 4, 5];
|
||||
int target = 9;
|
||||
List<List<int>> res = SubsetSumI(nums, target);
|
||||
Console.WriteLine("輸入陣列 nums = " + string.Join(", ", nums) + ", target = " + target);
|
||||
Console.WriteLine("所有和等於 " + target + " 的子集 res = ");
|
||||
foreach (var subset in res) {
|
||||
PrintUtil.PrintList(subset);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* File: subset_sum_i_naive.cs
|
||||
* Created Time: 2023-06-25
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_backtracking;
|
||||
|
||||
public class subset_sum_i_naive {
|
||||
/* 回溯演算法:子集和 I */
|
||||
void Backtrack(List<int> state, int target, int total, int[] choices, List<List<int>> res) {
|
||||
// 子集和等於 target 時,記錄解
|
||||
if (total == target) {
|
||||
res.Add(new List<int>(state));
|
||||
return;
|
||||
}
|
||||
// 走訪所有選擇
|
||||
for (int i = 0; i < choices.Length; i++) {
|
||||
// 剪枝:若子集和超過 target ,則跳過該選擇
|
||||
if (total + choices[i] > target) {
|
||||
continue;
|
||||
}
|
||||
// 嘗試:做出選擇,更新元素和 total
|
||||
state.Add(choices[i]);
|
||||
// 進行下一輪選擇
|
||||
Backtrack(state, target, total + choices[i], choices, res);
|
||||
// 回退:撤銷選擇,恢復到之前的狀態
|
||||
state.RemoveAt(state.Count - 1);
|
||||
}
|
||||
}
|
||||
|
||||
/* 求解子集和 I(包含重複子集) */
|
||||
List<List<int>> SubsetSumINaive(int[] nums, int target) {
|
||||
List<int> state = []; // 狀態(子集)
|
||||
int total = 0; // 子集和
|
||||
List<List<int>> res = []; // 結果串列(子集串列)
|
||||
Backtrack(state, target, total, nums, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int[] nums = [3, 4, 5];
|
||||
int target = 9;
|
||||
List<List<int>> res = SubsetSumINaive(nums, target);
|
||||
Console.WriteLine("輸入陣列 nums = " + string.Join(", ", nums) + ", target = " + target);
|
||||
Console.WriteLine("所有和等於 " + target + " 的子集 res = ");
|
||||
foreach (var subset in res) {
|
||||
PrintUtil.PrintList(subset);
|
||||
}
|
||||
Console.WriteLine("請注意,該方法輸出的結果包含重複集合");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* File: subset_sum_ii.cs
|
||||
* Created Time: 2023-06-25
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_backtracking;
|
||||
|
||||
public class subset_sum_ii {
|
||||
/* 回溯演算法:子集和 II */
|
||||
void Backtrack(List<int> state, int target, int[] choices, int start, List<List<int>> res) {
|
||||
// 子集和等於 target 時,記錄解
|
||||
if (target == 0) {
|
||||
res.Add(new List<int>(state));
|
||||
return;
|
||||
}
|
||||
// 走訪所有選擇
|
||||
// 剪枝二:從 start 開始走訪,避免生成重複子集
|
||||
// 剪枝三:從 start 開始走訪,避免重複選擇同一元素
|
||||
for (int i = start; i < choices.Length; i++) {
|
||||
// 剪枝一:若子集和超過 target ,則直接結束迴圈
|
||||
// 這是因為陣列已排序,後邊元素更大,子集和一定超過 target
|
||||
if (target - choices[i] < 0) {
|
||||
break;
|
||||
}
|
||||
// 剪枝四:如果該元素與左邊元素相等,說明該搜尋分支重複,直接跳過
|
||||
if (i > start && choices[i] == choices[i - 1]) {
|
||||
continue;
|
||||
}
|
||||
// 嘗試:做出選擇,更新 target, start
|
||||
state.Add(choices[i]);
|
||||
// 進行下一輪選擇
|
||||
Backtrack(state, target - choices[i], choices, i + 1, res);
|
||||
// 回退:撤銷選擇,恢復到之前的狀態
|
||||
state.RemoveAt(state.Count - 1);
|
||||
}
|
||||
}
|
||||
|
||||
/* 求解子集和 II */
|
||||
List<List<int>> SubsetSumII(int[] nums, int target) {
|
||||
List<int> state = []; // 狀態(子集)
|
||||
Array.Sort(nums); // 對 nums 進行排序
|
||||
int start = 0; // 走訪起始點
|
||||
List<List<int>> res = []; // 結果串列(子集串列)
|
||||
Backtrack(state, target, nums, start, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int[] nums = [4, 4, 5];
|
||||
int target = 9;
|
||||
List<List<int>> res = SubsetSumII(nums, target);
|
||||
Console.WriteLine("輸入陣列 nums = " + string.Join(", ", nums) + ", target = " + target);
|
||||
Console.WriteLine("所有和等於 " + target + " 的子集 res = ");
|
||||
foreach (var subset in res) {
|
||||
PrintUtil.PrintList(subset);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* File: iteration.cs
|
||||
* Created Time: 2023-08-28
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_computational_complexity;
|
||||
|
||||
public class iteration {
|
||||
/* for 迴圈 */
|
||||
int ForLoop(int n) {
|
||||
int res = 0;
|
||||
// 迴圈求和 1, 2, ..., n-1, n
|
||||
for (int i = 1; i <= n; i++) {
|
||||
res += i;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* while 迴圈 */
|
||||
int WhileLoop(int n) {
|
||||
int res = 0;
|
||||
int i = 1; // 初始化條件變數
|
||||
// 迴圈求和 1, 2, ..., n-1, n
|
||||
while (i <= n) {
|
||||
res += i;
|
||||
i += 1; // 更新條件變數
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* while 迴圈(兩次更新) */
|
||||
int WhileLoopII(int n) {
|
||||
int res = 0;
|
||||
int i = 1; // 初始化條件變數
|
||||
// 迴圈求和 1, 4, 10, ...
|
||||
while (i <= n) {
|
||||
res += i;
|
||||
// 更新條件變數
|
||||
i += 1;
|
||||
i *= 2;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* 雙層 for 迴圈 */
|
||||
string NestedForLoop(int n) {
|
||||
StringBuilder res = new();
|
||||
// 迴圈 i = 1, 2, ..., n-1, n
|
||||
for (int i = 1; i <= n; i++) {
|
||||
// 迴圈 j = 1, 2, ..., n-1, n
|
||||
for (int j = 1; j <= n; j++) {
|
||||
res.Append($"({i}, {j}), ");
|
||||
}
|
||||
}
|
||||
return res.ToString();
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
[Test]
|
||||
public void Test() {
|
||||
int n = 5;
|
||||
int res;
|
||||
|
||||
res = ForLoop(n);
|
||||
Console.WriteLine("\nfor 迴圈的求和結果 res = " + res);
|
||||
|
||||
res = WhileLoop(n);
|
||||
Console.WriteLine("\nwhile 迴圈的求和結果 res = " + res);
|
||||
|
||||
res = WhileLoopII(n);
|
||||
Console.WriteLine("\nwhile 迴圈(兩次更新)求和結果 res = " + res);
|
||||
|
||||
string resStr = NestedForLoop(n);
|
||||
Console.WriteLine("\n雙層 for 迴圈的走訪結果 " + resStr);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* File: recursion.cs
|
||||
* Created Time: 2023-08-28
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_computational_complexity;
|
||||
|
||||
public class recursion {
|
||||
/* 遞迴 */
|
||||
int Recur(int n) {
|
||||
// 終止條件
|
||||
if (n == 1)
|
||||
return 1;
|
||||
// 遞:遞迴呼叫
|
||||
int res = Recur(n - 1);
|
||||
// 迴:返回結果
|
||||
return n + res;
|
||||
}
|
||||
|
||||
/* 使用迭代模擬遞迴 */
|
||||
int ForLoopRecur(int n) {
|
||||
// 使用一個顯式的堆疊來模擬系統呼叫堆疊
|
||||
Stack<int> stack = new();
|
||||
int res = 0;
|
||||
// 遞:遞迴呼叫
|
||||
for (int i = n; i > 0; i--) {
|
||||
// 透過“入堆疊操作”模擬“遞”
|
||||
stack.Push(i);
|
||||
}
|
||||
// 迴:返回結果
|
||||
while (stack.Count > 0) {
|
||||
// 透過“出堆疊操作”模擬“迴”
|
||||
res += stack.Pop();
|
||||
}
|
||||
// res = 1+2+3+...+n
|
||||
return res;
|
||||
}
|
||||
|
||||
/* 尾遞迴 */
|
||||
int TailRecur(int n, int res) {
|
||||
// 終止條件
|
||||
if (n == 0)
|
||||
return res;
|
||||
// 尾遞迴呼叫
|
||||
return TailRecur(n - 1, res + n);
|
||||
}
|
||||
|
||||
/* 費波那契數列:遞迴 */
|
||||
int Fib(int n) {
|
||||
// 終止條件 f(1) = 0, f(2) = 1
|
||||
if (n == 1 || n == 2)
|
||||
return n - 1;
|
||||
// 遞迴呼叫 f(n) = f(n-1) + f(n-2)
|
||||
int res = Fib(n - 1) + Fib(n - 2);
|
||||
// 返回結果 f(n)
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
[Test]
|
||||
public void Test() {
|
||||
int n = 5;
|
||||
int res;
|
||||
|
||||
res = Recur(n);
|
||||
Console.WriteLine("\n遞迴函式的求和結果 res = " + res);
|
||||
|
||||
res = ForLoopRecur(n);
|
||||
Console.WriteLine("\n使用迭代模擬遞迴求和結果 res = " + res);
|
||||
|
||||
res = TailRecur(n, 0);
|
||||
Console.WriteLine("\n尾遞迴函式的求和結果 res = " + res);
|
||||
|
||||
res = Fib(n);
|
||||
Console.WriteLine("\n費波那契數列的第 " + n + " 項為 " + res);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* File: space_complexity.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_computational_complexity;
|
||||
|
||||
public class space_complexity {
|
||||
/* 函式 */
|
||||
int Function() {
|
||||
// 執行某些操作
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* 常數階 */
|
||||
void Constant(int n) {
|
||||
// 常數、變數、物件佔用 O(1) 空間
|
||||
int a = 0;
|
||||
int b = 0;
|
||||
int[] nums = new int[10000];
|
||||
ListNode node = new(0);
|
||||
// 迴圈中的變數佔用 O(1) 空間
|
||||
for (int i = 0; i < n; i++) {
|
||||
int c = 0;
|
||||
}
|
||||
// 迴圈中的函式佔用 O(1) 空間
|
||||
for (int i = 0; i < n; i++) {
|
||||
Function();
|
||||
}
|
||||
}
|
||||
|
||||
/* 線性階 */
|
||||
void Linear(int n) {
|
||||
// 長度為 n 的陣列佔用 O(n) 空間
|
||||
int[] nums = new int[n];
|
||||
// 長度為 n 的串列佔用 O(n) 空間
|
||||
List<ListNode> nodes = [];
|
||||
for (int i = 0; i < n; i++) {
|
||||
nodes.Add(new ListNode(i));
|
||||
}
|
||||
// 長度為 n 的雜湊表佔用 O(n) 空間
|
||||
Dictionary<int, string> map = [];
|
||||
for (int i = 0; i < n; i++) {
|
||||
map.Add(i, i.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
/* 線性階(遞迴實現) */
|
||||
void LinearRecur(int n) {
|
||||
Console.WriteLine("遞迴 n = " + n);
|
||||
if (n == 1) return;
|
||||
LinearRecur(n - 1);
|
||||
}
|
||||
|
||||
/* 平方階 */
|
||||
void Quadratic(int n) {
|
||||
// 矩陣佔用 O(n^2) 空間
|
||||
int[,] numMatrix = new int[n, n];
|
||||
// 二維串列佔用 O(n^2) 空間
|
||||
List<List<int>> numList = [];
|
||||
for (int i = 0; i < n; i++) {
|
||||
List<int> tmp = [];
|
||||
for (int j = 0; j < n; j++) {
|
||||
tmp.Add(0);
|
||||
}
|
||||
numList.Add(tmp);
|
||||
}
|
||||
}
|
||||
|
||||
/* 平方階(遞迴實現) */
|
||||
int QuadraticRecur(int n) {
|
||||
if (n <= 0) return 0;
|
||||
int[] nums = new int[n];
|
||||
Console.WriteLine("遞迴 n = " + n + " 中的 nums 長度 = " + nums.Length);
|
||||
return QuadraticRecur(n - 1);
|
||||
}
|
||||
|
||||
/* 指數階(建立滿二元樹) */
|
||||
TreeNode? BuildTree(int n) {
|
||||
if (n == 0) return null;
|
||||
TreeNode root = new(0) {
|
||||
left = BuildTree(n - 1),
|
||||
right = BuildTree(n - 1)
|
||||
};
|
||||
return root;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int n = 5;
|
||||
// 常數階
|
||||
Constant(n);
|
||||
// 線性階
|
||||
Linear(n);
|
||||
LinearRecur(n);
|
||||
// 平方階
|
||||
Quadratic(n);
|
||||
QuadraticRecur(n);
|
||||
// 指數階
|
||||
TreeNode? root = BuildTree(n);
|
||||
PrintUtil.PrintTree(root);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
/**
|
||||
* File: time_complexity.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_computational_complexity;
|
||||
|
||||
public class time_complexity {
|
||||
void Algorithm(int n) {
|
||||
int a = 1; // +0(技巧 1)
|
||||
a += n; // +0(技巧 1)
|
||||
// +n(技巧 2)
|
||||
for (int i = 0; i < 5 * n + 1; i++) {
|
||||
Console.WriteLine(0);
|
||||
}
|
||||
// +n*n(技巧 3)
|
||||
for (int i = 0; i < 2 * n; i++) {
|
||||
for (int j = 0; j < n + 1; j++) {
|
||||
Console.WriteLine(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 演算法 A 時間複雜度:常數階
|
||||
void AlgorithmA(int n) {
|
||||
Console.WriteLine(0);
|
||||
}
|
||||
|
||||
// 演算法 B 時間複雜度:線性階
|
||||
void AlgorithmB(int n) {
|
||||
for (int i = 0; i < n; i++) {
|
||||
Console.WriteLine(0);
|
||||
}
|
||||
}
|
||||
|
||||
// 演算法 C 時間複雜度:常數階
|
||||
void AlgorithmC(int n) {
|
||||
for (int i = 0; i < 1000000; i++) {
|
||||
Console.WriteLine(0);
|
||||
}
|
||||
}
|
||||
|
||||
/* 常數階 */
|
||||
int Constant(int n) {
|
||||
int count = 0;
|
||||
int size = 100000;
|
||||
for (int i = 0; i < size; i++)
|
||||
count++;
|
||||
return count;
|
||||
}
|
||||
|
||||
/* 線性階 */
|
||||
int Linear(int n) {
|
||||
int count = 0;
|
||||
for (int i = 0; i < n; i++)
|
||||
count++;
|
||||
return count;
|
||||
}
|
||||
|
||||
/* 線性階(走訪陣列) */
|
||||
int ArrayTraversal(int[] nums) {
|
||||
int count = 0;
|
||||
// 迴圈次數與陣列長度成正比
|
||||
foreach (int num in nums) {
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/* 平方階 */
|
||||
int Quadratic(int n) {
|
||||
int count = 0;
|
||||
// 迴圈次數與資料大小 n 成平方關係
|
||||
for (int i = 0; i < n; i++) {
|
||||
for (int j = 0; j < n; j++) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/* 平方階(泡沫排序) */
|
||||
int BubbleSort(int[] nums) {
|
||||
int count = 0; // 計數器
|
||||
// 外迴圈:未排序區間為 [0, i]
|
||||
for (int i = nums.Length - 1; i > 0; i--) {
|
||||
// 內迴圈:將未排序區間 [0, i] 中的最大元素交換至該區間的最右端
|
||||
for (int j = 0; j < i; j++) {
|
||||
if (nums[j] > nums[j + 1]) {
|
||||
// 交換 nums[j] 與 nums[j + 1]
|
||||
(nums[j + 1], nums[j]) = (nums[j], nums[j + 1]);
|
||||
count += 3; // 元素交換包含 3 個單元操作
|
||||
}
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/* 指數階(迴圈實現) */
|
||||
int Exponential(int n) {
|
||||
int count = 0, bas = 1;
|
||||
// 細胞每輪一分為二,形成數列 1, 2, 4, 8, ..., 2^(n-1)
|
||||
for (int i = 0; i < n; i++) {
|
||||
for (int j = 0; j < bas; j++) {
|
||||
count++;
|
||||
}
|
||||
bas *= 2;
|
||||
}
|
||||
// count = 1 + 2 + 4 + 8 + .. + 2^(n-1) = 2^n - 1
|
||||
return count;
|
||||
}
|
||||
|
||||
/* 指數階(遞迴實現) */
|
||||
int ExpRecur(int n) {
|
||||
if (n == 1) return 1;
|
||||
return ExpRecur(n - 1) + ExpRecur(n - 1) + 1;
|
||||
}
|
||||
|
||||
/* 對數階(迴圈實現) */
|
||||
int Logarithmic(int n) {
|
||||
int count = 0;
|
||||
while (n > 1) {
|
||||
n /= 2;
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/* 對數階(遞迴實現) */
|
||||
int LogRecur(int n) {
|
||||
if (n <= 1) return 0;
|
||||
return LogRecur(n / 2) + 1;
|
||||
}
|
||||
|
||||
/* 線性對數階 */
|
||||
int LinearLogRecur(int n) {
|
||||
if (n <= 1) return 1;
|
||||
int count = LinearLogRecur(n / 2) + LinearLogRecur(n / 2);
|
||||
for (int i = 0; i < n; i++) {
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/* 階乘階(遞迴實現) */
|
||||
int FactorialRecur(int n) {
|
||||
if (n == 0) return 1;
|
||||
int count = 0;
|
||||
// 從 1 個分裂出 n 個
|
||||
for (int i = 0; i < n; i++) {
|
||||
count += FactorialRecur(n - 1);
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
// 可以修改 n 執行,體會一下各種複雜度的操作數量變化趨勢
|
||||
int n = 8;
|
||||
Console.WriteLine("輸入資料大小 n = " + n);
|
||||
|
||||
int count = Constant(n);
|
||||
Console.WriteLine("常數階的操作數量 = " + count);
|
||||
|
||||
count = Linear(n);
|
||||
Console.WriteLine("線性階的操作數量 = " + count);
|
||||
count = ArrayTraversal(new int[n]);
|
||||
Console.WriteLine("線性階(走訪陣列)的操作數量 = " + count);
|
||||
|
||||
count = Quadratic(n);
|
||||
Console.WriteLine("平方階的操作數量 = " + count);
|
||||
int[] nums = new int[n];
|
||||
for (int i = 0; i < n; i++)
|
||||
nums[i] = n - i; // [n,n-1,...,2,1]
|
||||
count = BubbleSort(nums);
|
||||
Console.WriteLine("平方階(泡沫排序)的操作數量 = " + count);
|
||||
|
||||
count = Exponential(n);
|
||||
Console.WriteLine("指數階(迴圈實現)的操作數量 = " + count);
|
||||
count = ExpRecur(n);
|
||||
Console.WriteLine("指數階(遞迴實現)的操作數量 = " + count);
|
||||
|
||||
count = Logarithmic(n);
|
||||
Console.WriteLine("對數階(迴圈實現)的操作數量 = " + count);
|
||||
count = LogRecur(n);
|
||||
Console.WriteLine("對數階(遞迴實現)的操作數量 = " + count);
|
||||
|
||||
count = LinearLogRecur(n);
|
||||
Console.WriteLine("線性對數階(遞迴實現)的操作數量 = " + count);
|
||||
|
||||
count = FactorialRecur(n);
|
||||
Console.WriteLine("階乘階(遞迴實現)的操作數量 = " + count);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* File: worst_best_time_complexity.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_computational_complexity;
|
||||
|
||||
public class worst_best_time_complexity {
|
||||
/* 生成一個陣列,元素為 { 1, 2, ..., n },順序被打亂 */
|
||||
int[] RandomNumbers(int n) {
|
||||
int[] nums = new int[n];
|
||||
// 生成陣列 nums = { 1, 2, 3, ..., n }
|
||||
for (int i = 0; i < n; i++) {
|
||||
nums[i] = i + 1;
|
||||
}
|
||||
|
||||
// 隨機打亂陣列元素
|
||||
for (int i = 0; i < nums.Length; i++) {
|
||||
int index = new Random().Next(i, nums.Length);
|
||||
(nums[i], nums[index]) = (nums[index], nums[i]);
|
||||
}
|
||||
return nums;
|
||||
}
|
||||
|
||||
/* 查詢陣列 nums 中數字 1 所在索引 */
|
||||
int FindOne(int[] nums) {
|
||||
for (int i = 0; i < nums.Length; i++) {
|
||||
// 當元素 1 在陣列頭部時,達到最佳時間複雜度 O(1)
|
||||
// 當元素 1 在陣列尾部時,達到最差時間複雜度 O(n)
|
||||
if (nums[i] == 1)
|
||||
return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
/* Driver Code */
|
||||
[Test]
|
||||
public void Test() {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
int n = 100;
|
||||
int[] nums = RandomNumbers(n);
|
||||
int index = FindOne(nums);
|
||||
Console.WriteLine("\n陣列 [ 1, 2, ..., n ] 被打亂後 = " + string.Join(",", nums));
|
||||
Console.WriteLine("數字 1 的索引為 " + index);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* File: binary_search_recur.cs
|
||||
* Created Time: 2023-07-18
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_divide_and_conquer;
|
||||
|
||||
public class binary_search_recur {
|
||||
/* 二分搜尋:問題 f(i, j) */
|
||||
int DFS(int[] nums, int target, int i, int j) {
|
||||
// 若區間為空,代表無目標元素,則返回 -1
|
||||
if (i > j) {
|
||||
return -1;
|
||||
}
|
||||
// 計算中點索引 m
|
||||
int m = (i + j) / 2;
|
||||
if (nums[m] < target) {
|
||||
// 遞迴子問題 f(m+1, j)
|
||||
return DFS(nums, target, m + 1, j);
|
||||
} else if (nums[m] > target) {
|
||||
// 遞迴子問題 f(i, m-1)
|
||||
return DFS(nums, target, i, m - 1);
|
||||
} else {
|
||||
// 找到目標元素,返回其索引
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/* 二分搜尋 */
|
||||
int BinarySearch(int[] nums, int target) {
|
||||
int n = nums.Length;
|
||||
// 求解問題 f(0, n-1)
|
||||
return DFS(nums, target, 0, n - 1);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int target = 6;
|
||||
int[] nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35];
|
||||
|
||||
// 二分搜尋(雙閉區間)
|
||||
int index = BinarySearch(nums, target);
|
||||
Console.WriteLine("目標元素 6 的索引 = " + index);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* File: build_tree.cs
|
||||
* Created Time: 2023-07-18
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_divide_and_conquer;
|
||||
|
||||
public class build_tree {
|
||||
/* 構建二元樹:分治 */
|
||||
TreeNode? DFS(int[] preorder, Dictionary<int, int> inorderMap, int i, int l, int r) {
|
||||
// 子樹區間為空時終止
|
||||
if (r - l < 0)
|
||||
return null;
|
||||
// 初始化根節點
|
||||
TreeNode root = new(preorder[i]);
|
||||
// 查詢 m ,從而劃分左右子樹
|
||||
int m = inorderMap[preorder[i]];
|
||||
// 子問題:構建左子樹
|
||||
root.left = DFS(preorder, inorderMap, i + 1, l, m - 1);
|
||||
// 子問題:構建右子樹
|
||||
root.right = DFS(preorder, inorderMap, i + 1 + m - l, m + 1, r);
|
||||
// 返回根節點
|
||||
return root;
|
||||
}
|
||||
|
||||
/* 構建二元樹 */
|
||||
TreeNode? BuildTree(int[] preorder, int[] inorder) {
|
||||
// 初始化雜湊表,儲存 inorder 元素到索引的對映
|
||||
Dictionary<int, int> inorderMap = [];
|
||||
for (int i = 0; i < inorder.Length; i++) {
|
||||
inorderMap.TryAdd(inorder[i], i);
|
||||
}
|
||||
TreeNode? root = DFS(preorder, inorderMap, 0, 0, inorder.Length - 1);
|
||||
return root;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int[] preorder = [3, 9, 2, 1, 7];
|
||||
int[] inorder = [9, 3, 1, 2, 7];
|
||||
Console.WriteLine("前序走訪 = " + string.Join(", ", preorder));
|
||||
Console.WriteLine("中序走訪 = " + string.Join(", ", inorder));
|
||||
|
||||
TreeNode? root = BuildTree(preorder, inorder);
|
||||
Console.WriteLine("構建的二元樹為:");
|
||||
PrintUtil.PrintTree(root);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* File: hanota.cs
|
||||
* Created Time: 2023-07-18
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_divide_and_conquer;
|
||||
|
||||
public class hanota {
|
||||
/* 移動一個圓盤 */
|
||||
void Move(List<int> src, List<int> tar) {
|
||||
// 從 src 頂部拿出一個圓盤
|
||||
int pan = src[^1];
|
||||
src.RemoveAt(src.Count - 1);
|
||||
// 將圓盤放入 tar 頂部
|
||||
tar.Add(pan);
|
||||
}
|
||||
|
||||
/* 求解河內塔問題 f(i) */
|
||||
void DFS(int i, List<int> src, List<int> buf, List<int> tar) {
|
||||
// 若 src 只剩下一個圓盤,則直接將其移到 tar
|
||||
if (i == 1) {
|
||||
Move(src, tar);
|
||||
return;
|
||||
}
|
||||
// 子問題 f(i-1) :將 src 頂部 i-1 個圓盤藉助 tar 移到 buf
|
||||
DFS(i - 1, src, tar, buf);
|
||||
// 子問題 f(1) :將 src 剩餘一個圓盤移到 tar
|
||||
Move(src, tar);
|
||||
// 子問題 f(i-1) :將 buf 頂部 i-1 個圓盤藉助 src 移到 tar
|
||||
DFS(i - 1, buf, src, tar);
|
||||
}
|
||||
|
||||
/* 求解河內塔問題 */
|
||||
void SolveHanota(List<int> A, List<int> B, List<int> C) {
|
||||
int n = A.Count;
|
||||
// 將 A 頂部 n 個圓盤藉助 B 移到 C
|
||||
DFS(n, A, B, C);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
// 串列尾部是柱子頂部
|
||||
List<int> A = [5, 4, 3, 2, 1];
|
||||
List<int> B = [];
|
||||
List<int> C = [];
|
||||
Console.WriteLine("初始狀態下:");
|
||||
Console.WriteLine("A = " + string.Join(", ", A));
|
||||
Console.WriteLine("B = " + string.Join(", ", B));
|
||||
Console.WriteLine("C = " + string.Join(", ", C));
|
||||
|
||||
SolveHanota(A, B, C);
|
||||
|
||||
Console.WriteLine("圓盤移動完成後:");
|
||||
Console.WriteLine("A = " + string.Join(", ", A));
|
||||
Console.WriteLine("B = " + string.Join(", ", B));
|
||||
Console.WriteLine("C = " + string.Join(", ", C));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* File: climbing_stairs_backtrack.cs
|
||||
* Created Time: 2023-06-30
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class climbing_stairs_backtrack {
|
||||
/* 回溯 */
|
||||
void Backtrack(List<int> choices, int state, int n, List<int> res) {
|
||||
// 當爬到第 n 階時,方案數量加 1
|
||||
if (state == n)
|
||||
res[0]++;
|
||||
// 走訪所有選擇
|
||||
foreach (int choice in choices) {
|
||||
// 剪枝:不允許越過第 n 階
|
||||
if (state + choice > n)
|
||||
continue;
|
||||
// 嘗試:做出選擇,更新狀態
|
||||
Backtrack(choices, state + choice, n, res);
|
||||
// 回退
|
||||
}
|
||||
}
|
||||
|
||||
/* 爬樓梯:回溯 */
|
||||
int ClimbingStairsBacktrack(int n) {
|
||||
List<int> choices = [1, 2]; // 可選擇向上爬 1 階或 2 階
|
||||
int state = 0; // 從第 0 階開始爬
|
||||
List<int> res = [0]; // 使用 res[0] 記錄方案數量
|
||||
Backtrack(choices, state, n, res);
|
||||
return res[0];
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int n = 9;
|
||||
int res = ClimbingStairsBacktrack(n);
|
||||
Console.WriteLine($"爬 {n} 階樓梯共有 {res} 種方案");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* File: climbing_stairs_constraint_dp.cs
|
||||
* Created Time: 2023-07-03
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class climbing_stairs_constraint_dp {
|
||||
/* 帶約束爬樓梯:動態規劃 */
|
||||
int ClimbingStairsConstraintDP(int n) {
|
||||
if (n == 1 || n == 2) {
|
||||
return 1;
|
||||
}
|
||||
// 初始化 dp 表,用於儲存子問題的解
|
||||
int[,] dp = new int[n + 1, 3];
|
||||
// 初始狀態:預設最小子問題的解
|
||||
dp[1, 1] = 1;
|
||||
dp[1, 2] = 0;
|
||||
dp[2, 1] = 0;
|
||||
dp[2, 2] = 1;
|
||||
// 狀態轉移:從較小子問題逐步求解較大子問題
|
||||
for (int i = 3; i <= n; i++) {
|
||||
dp[i, 1] = dp[i - 1, 2];
|
||||
dp[i, 2] = dp[i - 2, 1] + dp[i - 2, 2];
|
||||
}
|
||||
return dp[n, 1] + dp[n, 2];
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int n = 9;
|
||||
int res = ClimbingStairsConstraintDP(n);
|
||||
Console.WriteLine($"爬 {n} 階樓梯共有 {res} 種方案");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* File: climbing_stairs_dfs.cs
|
||||
* Created Time: 2023-06-30
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class climbing_stairs_dfs {
|
||||
/* 搜尋 */
|
||||
int DFS(int i) {
|
||||
// 已知 dp[1] 和 dp[2] ,返回之
|
||||
if (i == 1 || i == 2)
|
||||
return i;
|
||||
// dp[i] = dp[i-1] + dp[i-2]
|
||||
int count = DFS(i - 1) + DFS(i - 2);
|
||||
return count;
|
||||
}
|
||||
|
||||
/* 爬樓梯:搜尋 */
|
||||
int ClimbingStairsDFS(int n) {
|
||||
return DFS(n);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int n = 9;
|
||||
int res = ClimbingStairsDFS(n);
|
||||
Console.WriteLine($"爬 {n} 階樓梯共有 {res} 種方案");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* File: climbing_stairs_dfs_mem.cs
|
||||
* Created Time: 2023-06-30
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class climbing_stairs_dfs_mem {
|
||||
/* 記憶化搜尋 */
|
||||
int DFS(int i, int[] mem) {
|
||||
// 已知 dp[1] 和 dp[2] ,返回之
|
||||
if (i == 1 || i == 2)
|
||||
return i;
|
||||
// 若存在記錄 dp[i] ,則直接返回之
|
||||
if (mem[i] != -1)
|
||||
return mem[i];
|
||||
// dp[i] = dp[i-1] + dp[i-2]
|
||||
int count = DFS(i - 1, mem) + DFS(i - 2, mem);
|
||||
// 記錄 dp[i]
|
||||
mem[i] = count;
|
||||
return count;
|
||||
}
|
||||
|
||||
/* 爬樓梯:記憶化搜尋 */
|
||||
int ClimbingStairsDFSMem(int n) {
|
||||
// mem[i] 記錄爬到第 i 階的方案總數,-1 代表無記錄
|
||||
int[] mem = new int[n + 1];
|
||||
Array.Fill(mem, -1);
|
||||
return DFS(n, mem);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int n = 9;
|
||||
int res = ClimbingStairsDFSMem(n);
|
||||
Console.WriteLine($"爬 {n} 階樓梯共有 {res} 種方案");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* File: climbing_stairs_dp.cs
|
||||
* Created Time: 2023-06-30
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class climbing_stairs_dp {
|
||||
/* 爬樓梯:動態規劃 */
|
||||
int ClimbingStairsDP(int n) {
|
||||
if (n == 1 || n == 2)
|
||||
return n;
|
||||
// 初始化 dp 表,用於儲存子問題的解
|
||||
int[] dp = new int[n + 1];
|
||||
// 初始狀態:預設最小子問題的解
|
||||
dp[1] = 1;
|
||||
dp[2] = 2;
|
||||
// 狀態轉移:從較小子問題逐步求解較大子問題
|
||||
for (int i = 3; i <= n; i++) {
|
||||
dp[i] = dp[i - 1] + dp[i - 2];
|
||||
}
|
||||
return dp[n];
|
||||
}
|
||||
|
||||
/* 爬樓梯:空間最佳化後的動態規劃 */
|
||||
int ClimbingStairsDPComp(int n) {
|
||||
if (n == 1 || n == 2)
|
||||
return n;
|
||||
int a = 1, b = 2;
|
||||
for (int i = 3; i <= n; i++) {
|
||||
int tmp = b;
|
||||
b = a + b;
|
||||
a = tmp;
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int n = 9;
|
||||
|
||||
int res = ClimbingStairsDP(n);
|
||||
Console.WriteLine($"爬 {n} 階樓梯共有 {res} 種方案");
|
||||
|
||||
res = ClimbingStairsDPComp(n);
|
||||
Console.WriteLine($"爬 {n} 階樓梯共有 {res} 種方案");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* File: coin_change.cs
|
||||
* Created Time: 2023-07-12
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class coin_change {
|
||||
/* 零錢兌換:動態規劃 */
|
||||
int CoinChangeDP(int[] coins, int amt) {
|
||||
int n = coins.Length;
|
||||
int MAX = amt + 1;
|
||||
// 初始化 dp 表
|
||||
int[,] dp = new int[n + 1, amt + 1];
|
||||
// 狀態轉移:首行首列
|
||||
for (int a = 1; a <= amt; a++) {
|
||||
dp[0, a] = MAX;
|
||||
}
|
||||
// 狀態轉移:其餘行和列
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int a = 1; a <= amt; a++) {
|
||||
if (coins[i - 1] > a) {
|
||||
// 若超過目標金額,則不選硬幣 i
|
||||
dp[i, a] = dp[i - 1, a];
|
||||
} else {
|
||||
// 不選和選硬幣 i 這兩種方案的較小值
|
||||
dp[i, a] = Math.Min(dp[i - 1, a], dp[i, a - coins[i - 1]] + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n, amt] != MAX ? dp[n, amt] : -1;
|
||||
}
|
||||
|
||||
/* 零錢兌換:空間最佳化後的動態規劃 */
|
||||
int CoinChangeDPComp(int[] coins, int amt) {
|
||||
int n = coins.Length;
|
||||
int MAX = amt + 1;
|
||||
// 初始化 dp 表
|
||||
int[] dp = new int[amt + 1];
|
||||
Array.Fill(dp, MAX);
|
||||
dp[0] = 0;
|
||||
// 狀態轉移
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int a = 1; a <= amt; a++) {
|
||||
if (coins[i - 1] > a) {
|
||||
// 若超過目標金額,則不選硬幣 i
|
||||
dp[a] = dp[a];
|
||||
} else {
|
||||
// 不選和選硬幣 i 這兩種方案的較小值
|
||||
dp[a] = Math.Min(dp[a], dp[a - coins[i - 1]] + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[amt] != MAX ? dp[amt] : -1;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int[] coins = [1, 2, 5];
|
||||
int amt = 4;
|
||||
|
||||
// 動態規劃
|
||||
int res = CoinChangeDP(coins, amt);
|
||||
Console.WriteLine("湊到目標金額所需的最少硬幣數量為 " + res);
|
||||
|
||||
// 空間最佳化後的動態規劃
|
||||
res = CoinChangeDPComp(coins, amt);
|
||||
Console.WriteLine("湊到目標金額所需的最少硬幣數量為 " + res);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* File: coin_change_ii.cs
|
||||
* Created Time: 2023-07-12
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class coin_change_ii {
|
||||
/* 零錢兌換 II:動態規劃 */
|
||||
int CoinChangeIIDP(int[] coins, int amt) {
|
||||
int n = coins.Length;
|
||||
// 初始化 dp 表
|
||||
int[,] dp = new int[n + 1, amt + 1];
|
||||
// 初始化首列
|
||||
for (int i = 0; i <= n; i++) {
|
||||
dp[i, 0] = 1;
|
||||
}
|
||||
// 狀態轉移
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int a = 1; a <= amt; a++) {
|
||||
if (coins[i - 1] > a) {
|
||||
// 若超過目標金額,則不選硬幣 i
|
||||
dp[i, a] = dp[i - 1, a];
|
||||
} else {
|
||||
// 不選和選硬幣 i 這兩種方案之和
|
||||
dp[i, a] = dp[i - 1, a] + dp[i, a - coins[i - 1]];
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n, amt];
|
||||
}
|
||||
|
||||
/* 零錢兌換 II:空間最佳化後的動態規劃 */
|
||||
int CoinChangeIIDPComp(int[] coins, int amt) {
|
||||
int n = coins.Length;
|
||||
// 初始化 dp 表
|
||||
int[] dp = new int[amt + 1];
|
||||
dp[0] = 1;
|
||||
// 狀態轉移
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int a = 1; a <= amt; a++) {
|
||||
if (coins[i - 1] > a) {
|
||||
// 若超過目標金額,則不選硬幣 i
|
||||
dp[a] = dp[a];
|
||||
} else {
|
||||
// 不選和選硬幣 i 這兩種方案之和
|
||||
dp[a] = dp[a] + dp[a - coins[i - 1]];
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[amt];
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int[] coins = [1, 2, 5];
|
||||
int amt = 5;
|
||||
|
||||
// 動態規劃
|
||||
int res = CoinChangeIIDP(coins, amt);
|
||||
Console.WriteLine("湊出目標金額的硬幣組合數量為 " + res);
|
||||
|
||||
// 空間最佳化後的動態規劃
|
||||
res = CoinChangeIIDPComp(coins, amt);
|
||||
Console.WriteLine("湊出目標金額的硬幣組合數量為 " + res);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
/**
|
||||
* File: edit_distance.cs
|
||||
* Created Time: 2023-07-14
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class edit_distance {
|
||||
/* 編輯距離:暴力搜尋 */
|
||||
int EditDistanceDFS(string s, string t, int i, int j) {
|
||||
// 若 s 和 t 都為空,則返回 0
|
||||
if (i == 0 && j == 0)
|
||||
return 0;
|
||||
// 若 s 為空,則返回 t 長度
|
||||
if (i == 0)
|
||||
return j;
|
||||
// 若 t 為空,則返回 s 長度
|
||||
if (j == 0)
|
||||
return i;
|
||||
// 若兩字元相等,則直接跳過此兩字元
|
||||
if (s[i - 1] == t[j - 1])
|
||||
return EditDistanceDFS(s, t, i - 1, j - 1);
|
||||
// 最少編輯步數 = 插入、刪除、替換這三種操作的最少編輯步數 + 1
|
||||
int insert = EditDistanceDFS(s, t, i, j - 1);
|
||||
int delete = EditDistanceDFS(s, t, i - 1, j);
|
||||
int replace = EditDistanceDFS(s, t, i - 1, j - 1);
|
||||
// 返回最少編輯步數
|
||||
return Math.Min(Math.Min(insert, delete), replace) + 1;
|
||||
}
|
||||
|
||||
/* 編輯距離:記憶化搜尋 */
|
||||
int EditDistanceDFSMem(string s, string t, int[][] mem, int i, int j) {
|
||||
// 若 s 和 t 都為空,則返回 0
|
||||
if (i == 0 && j == 0)
|
||||
return 0;
|
||||
// 若 s 為空,則返回 t 長度
|
||||
if (i == 0)
|
||||
return j;
|
||||
// 若 t 為空,則返回 s 長度
|
||||
if (j == 0)
|
||||
return i;
|
||||
// 若已有記錄,則直接返回之
|
||||
if (mem[i][j] != -1)
|
||||
return mem[i][j];
|
||||
// 若兩字元相等,則直接跳過此兩字元
|
||||
if (s[i - 1] == t[j - 1])
|
||||
return EditDistanceDFSMem(s, t, mem, i - 1, j - 1);
|
||||
// 最少編輯步數 = 插入、刪除、替換這三種操作的最少編輯步數 + 1
|
||||
int insert = EditDistanceDFSMem(s, t, mem, i, j - 1);
|
||||
int delete = EditDistanceDFSMem(s, t, mem, i - 1, j);
|
||||
int replace = EditDistanceDFSMem(s, t, mem, i - 1, j - 1);
|
||||
// 記錄並返回最少編輯步數
|
||||
mem[i][j] = Math.Min(Math.Min(insert, delete), replace) + 1;
|
||||
return mem[i][j];
|
||||
}
|
||||
|
||||
/* 編輯距離:動態規劃 */
|
||||
int EditDistanceDP(string s, string t) {
|
||||
int n = s.Length, m = t.Length;
|
||||
int[,] dp = new int[n + 1, m + 1];
|
||||
// 狀態轉移:首行首列
|
||||
for (int i = 1; i <= n; i++) {
|
||||
dp[i, 0] = i;
|
||||
}
|
||||
for (int j = 1; j <= m; j++) {
|
||||
dp[0, j] = j;
|
||||
}
|
||||
// 狀態轉移:其餘行和列
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int j = 1; j <= m; j++) {
|
||||
if (s[i - 1] == t[j - 1]) {
|
||||
// 若兩字元相等,則直接跳過此兩字元
|
||||
dp[i, j] = dp[i - 1, j - 1];
|
||||
} else {
|
||||
// 最少編輯步數 = 插入、刪除、替換這三種操作的最少編輯步數 + 1
|
||||
dp[i, j] = Math.Min(Math.Min(dp[i, j - 1], dp[i - 1, j]), dp[i - 1, j - 1]) + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n, m];
|
||||
}
|
||||
|
||||
/* 編輯距離:空間最佳化後的動態規劃 */
|
||||
int EditDistanceDPComp(string s, string t) {
|
||||
int n = s.Length, m = t.Length;
|
||||
int[] dp = new int[m + 1];
|
||||
// 狀態轉移:首行
|
||||
for (int j = 1; j <= m; j++) {
|
||||
dp[j] = j;
|
||||
}
|
||||
// 狀態轉移:其餘行
|
||||
for (int i = 1; i <= n; i++) {
|
||||
// 狀態轉移:首列
|
||||
int leftup = dp[0]; // 暫存 dp[i-1, j-1]
|
||||
dp[0] = i;
|
||||
// 狀態轉移:其餘列
|
||||
for (int j = 1; j <= m; j++) {
|
||||
int temp = dp[j];
|
||||
if (s[i - 1] == t[j - 1]) {
|
||||
// 若兩字元相等,則直接跳過此兩字元
|
||||
dp[j] = leftup;
|
||||
} else {
|
||||
// 最少編輯步數 = 插入、刪除、替換這三種操作的最少編輯步數 + 1
|
||||
dp[j] = Math.Min(Math.Min(dp[j - 1], dp[j]), leftup) + 1;
|
||||
}
|
||||
leftup = temp; // 更新為下一輪的 dp[i-1, j-1]
|
||||
}
|
||||
}
|
||||
return dp[m];
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
string s = "bag";
|
||||
string t = "pack";
|
||||
int n = s.Length, m = t.Length;
|
||||
|
||||
// 暴力搜尋
|
||||
int res = EditDistanceDFS(s, t, n, m);
|
||||
Console.WriteLine("將 " + s + " 更改為 " + t + " 最少需要編輯 " + res + " 步");
|
||||
|
||||
// 記憶化搜尋
|
||||
int[][] mem = new int[n + 1][];
|
||||
for (int i = 0; i <= n; i++) {
|
||||
mem[i] = new int[m + 1];
|
||||
Array.Fill(mem[i], -1);
|
||||
}
|
||||
|
||||
res = EditDistanceDFSMem(s, t, mem, n, m);
|
||||
Console.WriteLine("將 " + s + " 更改為 " + t + " 最少需要編輯 " + res + " 步");
|
||||
|
||||
// 動態規劃
|
||||
res = EditDistanceDP(s, t);
|
||||
Console.WriteLine("將 " + s + " 更改為 " + t + " 最少需要編輯 " + res + " 步");
|
||||
|
||||
// 空間最佳化後的動態規劃
|
||||
res = EditDistanceDPComp(s, t);
|
||||
Console.WriteLine("將 " + s + " 更改為 " + t + " 最少需要編輯 " + res + " 步");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* File: knapsack.cs
|
||||
* Created Time: 2023-07-07
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class knapsack {
|
||||
/* 0-1 背包:暴力搜尋 */
|
||||
int KnapsackDFS(int[] weight, int[] val, int i, int c) {
|
||||
// 若已選完所有物品或背包無剩餘容量,則返回價值 0
|
||||
if (i == 0 || c == 0) {
|
||||
return 0;
|
||||
}
|
||||
// 若超過背包容量,則只能選擇不放入背包
|
||||
if (weight[i - 1] > c) {
|
||||
return KnapsackDFS(weight, val, i - 1, c);
|
||||
}
|
||||
// 計算不放入和放入物品 i 的最大價值
|
||||
int no = KnapsackDFS(weight, val, i - 1, c);
|
||||
int yes = KnapsackDFS(weight, val, i - 1, c - weight[i - 1]) + val[i - 1];
|
||||
// 返回兩種方案中價值更大的那一個
|
||||
return Math.Max(no, yes);
|
||||
}
|
||||
|
||||
/* 0-1 背包:記憶化搜尋 */
|
||||
int KnapsackDFSMem(int[] weight, int[] val, int[][] mem, int i, int c) {
|
||||
// 若已選完所有物品或背包無剩餘容量,則返回價值 0
|
||||
if (i == 0 || c == 0) {
|
||||
return 0;
|
||||
}
|
||||
// 若已有記錄,則直接返回
|
||||
if (mem[i][c] != -1) {
|
||||
return mem[i][c];
|
||||
}
|
||||
// 若超過背包容量,則只能選擇不放入背包
|
||||
if (weight[i - 1] > c) {
|
||||
return KnapsackDFSMem(weight, val, mem, i - 1, c);
|
||||
}
|
||||
// 計算不放入和放入物品 i 的最大價值
|
||||
int no = KnapsackDFSMem(weight, val, mem, i - 1, c);
|
||||
int yes = KnapsackDFSMem(weight, val, mem, i - 1, c - weight[i - 1]) + val[i - 1];
|
||||
// 記錄並返回兩種方案中價值更大的那一個
|
||||
mem[i][c] = Math.Max(no, yes);
|
||||
return mem[i][c];
|
||||
}
|
||||
|
||||
/* 0-1 背包:動態規劃 */
|
||||
int KnapsackDP(int[] weight, int[] val, int cap) {
|
||||
int n = weight.Length;
|
||||
// 初始化 dp 表
|
||||
int[,] dp = new int[n + 1, cap + 1];
|
||||
// 狀態轉移
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int c = 1; c <= cap; c++) {
|
||||
if (weight[i - 1] > c) {
|
||||
// 若超過背包容量,則不選物品 i
|
||||
dp[i, c] = dp[i - 1, c];
|
||||
} else {
|
||||
// 不選和選物品 i 這兩種方案的較大值
|
||||
dp[i, c] = Math.Max(dp[i - 1, c - weight[i - 1]] + val[i - 1], dp[i - 1, c]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n, cap];
|
||||
}
|
||||
|
||||
/* 0-1 背包:空間最佳化後的動態規劃 */
|
||||
int KnapsackDPComp(int[] weight, int[] val, int cap) {
|
||||
int n = weight.Length;
|
||||
// 初始化 dp 表
|
||||
int[] dp = new int[cap + 1];
|
||||
// 狀態轉移
|
||||
for (int i = 1; i <= n; i++) {
|
||||
// 倒序走訪
|
||||
for (int c = cap; c > 0; c--) {
|
||||
if (weight[i - 1] > c) {
|
||||
// 若超過背包容量,則不選物品 i
|
||||
dp[c] = dp[c];
|
||||
} else {
|
||||
// 不選和選物品 i 這兩種方案的較大值
|
||||
dp[c] = Math.Max(dp[c], dp[c - weight[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[cap];
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int[] weight = [10, 20, 30, 40, 50];
|
||||
int[] val = [50, 120, 150, 210, 240];
|
||||
int cap = 50;
|
||||
int n = weight.Length;
|
||||
|
||||
// 暴力搜尋
|
||||
int res = KnapsackDFS(weight, val, n, cap);
|
||||
Console.WriteLine("不超過背包容量的最大物品價值為 " + res);
|
||||
|
||||
// 記憶化搜尋
|
||||
int[][] mem = new int[n + 1][];
|
||||
for (int i = 0; i <= n; i++) {
|
||||
mem[i] = new int[cap + 1];
|
||||
Array.Fill(mem[i], -1);
|
||||
}
|
||||
res = KnapsackDFSMem(weight, val, mem, n, cap);
|
||||
Console.WriteLine("不超過背包容量的最大物品價值為 " + res);
|
||||
|
||||
// 動態規劃
|
||||
res = KnapsackDP(weight, val, cap);
|
||||
Console.WriteLine("不超過背包容量的最大物品價值為 " + res);
|
||||
|
||||
// 空間最佳化後的動態規劃
|
||||
res = KnapsackDPComp(weight, val, cap);
|
||||
Console.WriteLine("不超過背包容量的最大物品價值為 " + res);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* File: min_cost_climbing_stairs_dp.cs
|
||||
* Created Time: 2023-06-30
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class min_cost_climbing_stairs_dp {
|
||||
/* 爬樓梯最小代價:動態規劃 */
|
||||
int MinCostClimbingStairsDP(int[] cost) {
|
||||
int n = cost.Length - 1;
|
||||
if (n == 1 || n == 2)
|
||||
return cost[n];
|
||||
// 初始化 dp 表,用於儲存子問題的解
|
||||
int[] dp = new int[n + 1];
|
||||
// 初始狀態:預設最小子問題的解
|
||||
dp[1] = cost[1];
|
||||
dp[2] = cost[2];
|
||||
// 狀態轉移:從較小子問題逐步求解較大子問題
|
||||
for (int i = 3; i <= n; i++) {
|
||||
dp[i] = Math.Min(dp[i - 1], dp[i - 2]) + cost[i];
|
||||
}
|
||||
return dp[n];
|
||||
}
|
||||
|
||||
/* 爬樓梯最小代價:空間最佳化後的動態規劃 */
|
||||
int MinCostClimbingStairsDPComp(int[] cost) {
|
||||
int n = cost.Length - 1;
|
||||
if (n == 1 || n == 2)
|
||||
return cost[n];
|
||||
int a = cost[1], b = cost[2];
|
||||
for (int i = 3; i <= n; i++) {
|
||||
int tmp = b;
|
||||
b = Math.Min(a, tmp) + cost[i];
|
||||
a = tmp;
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int[] cost = [0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1];
|
||||
Console.WriteLine("輸入樓梯的代價串列為");
|
||||
PrintUtil.PrintList(cost);
|
||||
|
||||
int res = MinCostClimbingStairsDP(cost);
|
||||
Console.WriteLine($"爬完樓梯的最低代價為 {res}");
|
||||
|
||||
res = MinCostClimbingStairsDPComp(cost);
|
||||
Console.WriteLine($"爬完樓梯的最低代價為 {res}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* File: min_path_sum.cs
|
||||
* Created Time: 2023-07-10
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class min_path_sum {
|
||||
/* 最小路徑和:暴力搜尋 */
|
||||
int MinPathSumDFS(int[][] grid, int i, int j) {
|
||||
// 若為左上角單元格,則終止搜尋
|
||||
if (i == 0 && j == 0) {
|
||||
return grid[0][0];
|
||||
}
|
||||
// 若行列索引越界,則返回 +∞ 代價
|
||||
if (i < 0 || j < 0) {
|
||||
return int.MaxValue;
|
||||
}
|
||||
// 計算從左上角到 (i-1, j) 和 (i, j-1) 的最小路徑代價
|
||||
int up = MinPathSumDFS(grid, i - 1, j);
|
||||
int left = MinPathSumDFS(grid, i, j - 1);
|
||||
// 返回從左上角到 (i, j) 的最小路徑代價
|
||||
return Math.Min(left, up) + grid[i][j];
|
||||
}
|
||||
|
||||
/* 最小路徑和:記憶化搜尋 */
|
||||
int MinPathSumDFSMem(int[][] grid, int[][] mem, int i, int j) {
|
||||
// 若為左上角單元格,則終止搜尋
|
||||
if (i == 0 && j == 0) {
|
||||
return grid[0][0];
|
||||
}
|
||||
// 若行列索引越界,則返回 +∞ 代價
|
||||
if (i < 0 || j < 0) {
|
||||
return int.MaxValue;
|
||||
}
|
||||
// 若已有記錄,則直接返回
|
||||
if (mem[i][j] != -1) {
|
||||
return mem[i][j];
|
||||
}
|
||||
// 左邊和上邊單元格的最小路徑代價
|
||||
int up = MinPathSumDFSMem(grid, mem, i - 1, j);
|
||||
int left = MinPathSumDFSMem(grid, mem, i, j - 1);
|
||||
// 記錄並返回左上角到 (i, j) 的最小路徑代價
|
||||
mem[i][j] = Math.Min(left, up) + grid[i][j];
|
||||
return mem[i][j];
|
||||
}
|
||||
|
||||
/* 最小路徑和:動態規劃 */
|
||||
int MinPathSumDP(int[][] grid) {
|
||||
int n = grid.Length, m = grid[0].Length;
|
||||
// 初始化 dp 表
|
||||
int[,] dp = new int[n, m];
|
||||
dp[0, 0] = grid[0][0];
|
||||
// 狀態轉移:首行
|
||||
for (int j = 1; j < m; j++) {
|
||||
dp[0, j] = dp[0, j - 1] + grid[0][j];
|
||||
}
|
||||
// 狀態轉移:首列
|
||||
for (int i = 1; i < n; i++) {
|
||||
dp[i, 0] = dp[i - 1, 0] + grid[i][0];
|
||||
}
|
||||
// 狀態轉移:其餘行和列
|
||||
for (int i = 1; i < n; i++) {
|
||||
for (int j = 1; j < m; j++) {
|
||||
dp[i, j] = Math.Min(dp[i, j - 1], dp[i - 1, j]) + grid[i][j];
|
||||
}
|
||||
}
|
||||
return dp[n - 1, m - 1];
|
||||
}
|
||||
|
||||
/* 最小路徑和:空間最佳化後的動態規劃 */
|
||||
int MinPathSumDPComp(int[][] grid) {
|
||||
int n = grid.Length, m = grid[0].Length;
|
||||
// 初始化 dp 表
|
||||
int[] dp = new int[m];
|
||||
dp[0] = grid[0][0];
|
||||
// 狀態轉移:首行
|
||||
for (int j = 1; j < m; j++) {
|
||||
dp[j] = dp[j - 1] + grid[0][j];
|
||||
}
|
||||
// 狀態轉移:其餘行
|
||||
for (int i = 1; i < n; i++) {
|
||||
// 狀態轉移:首列
|
||||
dp[0] = dp[0] + grid[i][0];
|
||||
// 狀態轉移:其餘列
|
||||
for (int j = 1; j < m; j++) {
|
||||
dp[j] = Math.Min(dp[j - 1], dp[j]) + grid[i][j];
|
||||
}
|
||||
}
|
||||
return dp[m - 1];
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int[][] grid =
|
||||
[
|
||||
[1, 3, 1, 5],
|
||||
[2, 2, 4, 2],
|
||||
[5, 3, 2, 1],
|
||||
[4, 3, 5, 2]
|
||||
];
|
||||
|
||||
int n = grid.Length, m = grid[0].Length;
|
||||
|
||||
// 暴力搜尋
|
||||
int res = MinPathSumDFS(grid, n - 1, m - 1);
|
||||
Console.WriteLine("從左上角到右下角的做小路徑和為 " + res);
|
||||
|
||||
// 記憶化搜尋
|
||||
int[][] mem = new int[n][];
|
||||
for (int i = 0; i < n; i++) {
|
||||
mem[i] = new int[m];
|
||||
Array.Fill(mem[i], -1);
|
||||
}
|
||||
res = MinPathSumDFSMem(grid, mem, n - 1, m - 1);
|
||||
Console.WriteLine("從左上角到右下角的做小路徑和為 " + res);
|
||||
|
||||
// 動態規劃
|
||||
res = MinPathSumDP(grid);
|
||||
Console.WriteLine("從左上角到右下角的做小路徑和為 " + res);
|
||||
|
||||
// 空間最佳化後的動態規劃
|
||||
res = MinPathSumDPComp(grid);
|
||||
Console.WriteLine("從左上角到右下角的做小路徑和為 " + res);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* File: unbounded_knapsack.cs
|
||||
* Created Time: 2023-07-12
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class unbounded_knapsack {
|
||||
/* 完全背包:動態規劃 */
|
||||
int UnboundedKnapsackDP(int[] wgt, int[] val, int cap) {
|
||||
int n = wgt.Length;
|
||||
// 初始化 dp 表
|
||||
int[,] dp = new int[n + 1, cap + 1];
|
||||
// 狀態轉移
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int c = 1; c <= cap; c++) {
|
||||
if (wgt[i - 1] > c) {
|
||||
// 若超過背包容量,則不選物品 i
|
||||
dp[i, c] = dp[i - 1, c];
|
||||
} else {
|
||||
// 不選和選物品 i 這兩種方案的較大值
|
||||
dp[i, c] = Math.Max(dp[i - 1, c], dp[i, c - wgt[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n, cap];
|
||||
}
|
||||
|
||||
/* 完全背包:空間最佳化後的動態規劃 */
|
||||
int UnboundedKnapsackDPComp(int[] wgt, int[] val, int cap) {
|
||||
int n = wgt.Length;
|
||||
// 初始化 dp 表
|
||||
int[] dp = new int[cap + 1];
|
||||
// 狀態轉移
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int c = 1; c <= cap; c++) {
|
||||
if (wgt[i - 1] > c) {
|
||||
// 若超過背包容量,則不選物品 i
|
||||
dp[c] = dp[c];
|
||||
} else {
|
||||
// 不選和選物品 i 這兩種方案的較大值
|
||||
dp[c] = Math.Max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[cap];
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int[] wgt = [1, 2, 3];
|
||||
int[] val = [5, 11, 15];
|
||||
int cap = 4;
|
||||
|
||||
// 動態規劃
|
||||
int res = UnboundedKnapsackDP(wgt, val, cap);
|
||||
Console.WriteLine("不超過背包容量的最大物品價值為 " + res);
|
||||
|
||||
// 空間最佳化後的動態規劃
|
||||
res = UnboundedKnapsackDPComp(wgt, val, cap);
|
||||
Console.WriteLine("不超過背包容量的最大物品價值為 " + res);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* File: graph_adjacency_list.cs
|
||||
* Created Time: 2023-02-06
|
||||
* Author: zjkung1123 (zjkung1123@gmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_graph;
|
||||
|
||||
/* 基於鄰接表實現的無向圖類別 */
|
||||
public class GraphAdjList {
|
||||
// 鄰接表,key:頂點,value:該頂點的所有鄰接頂點
|
||||
public Dictionary<Vertex, List<Vertex>> adjList;
|
||||
|
||||
/* 建構子 */
|
||||
public GraphAdjList(Vertex[][] edges) {
|
||||
adjList = [];
|
||||
// 新增所有頂點和邊
|
||||
foreach (Vertex[] edge in edges) {
|
||||
AddVertex(edge[0]);
|
||||
AddVertex(edge[1]);
|
||||
AddEdge(edge[0], edge[1]);
|
||||
}
|
||||
}
|
||||
|
||||
/* 獲取頂點數量 */
|
||||
int Size() {
|
||||
return adjList.Count;
|
||||
}
|
||||
|
||||
/* 新增邊 */
|
||||
public void AddEdge(Vertex vet1, Vertex vet2) {
|
||||
if (!adjList.ContainsKey(vet1) || !adjList.ContainsKey(vet2) || vet1 == vet2)
|
||||
throw new InvalidOperationException();
|
||||
// 新增邊 vet1 - vet2
|
||||
adjList[vet1].Add(vet2);
|
||||
adjList[vet2].Add(vet1);
|
||||
}
|
||||
|
||||
/* 刪除邊 */
|
||||
public void RemoveEdge(Vertex vet1, Vertex vet2) {
|
||||
if (!adjList.ContainsKey(vet1) || !adjList.ContainsKey(vet2) || vet1 == vet2)
|
||||
throw new InvalidOperationException();
|
||||
// 刪除邊 vet1 - vet2
|
||||
adjList[vet1].Remove(vet2);
|
||||
adjList[vet2].Remove(vet1);
|
||||
}
|
||||
|
||||
/* 新增頂點 */
|
||||
public void AddVertex(Vertex vet) {
|
||||
if (adjList.ContainsKey(vet))
|
||||
return;
|
||||
// 在鄰接表中新增一個新鏈結串列
|
||||
adjList.Add(vet, []);
|
||||
}
|
||||
|
||||
/* 刪除頂點 */
|
||||
public void RemoveVertex(Vertex vet) {
|
||||
if (!adjList.ContainsKey(vet))
|
||||
throw new InvalidOperationException();
|
||||
// 在鄰接表中刪除頂點 vet 對應的鏈結串列
|
||||
adjList.Remove(vet);
|
||||
// 走訪其他頂點的鏈結串列,刪除所有包含 vet 的邊
|
||||
foreach (List<Vertex> list in adjList.Values) {
|
||||
list.Remove(vet);
|
||||
}
|
||||
}
|
||||
|
||||
/* 列印鄰接表 */
|
||||
public void Print() {
|
||||
Console.WriteLine("鄰接表 =");
|
||||
foreach (KeyValuePair<Vertex, List<Vertex>> pair in adjList) {
|
||||
List<int> tmp = [];
|
||||
foreach (Vertex vertex in pair.Value)
|
||||
tmp.Add(vertex.val);
|
||||
Console.WriteLine(pair.Key.val + ": [" + string.Join(", ", tmp) + "],");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class graph_adjacency_list {
|
||||
[Test]
|
||||
public void Test() {
|
||||
/* 初始化無向圖 */
|
||||
Vertex[] v = Vertex.ValsToVets([1, 3, 2, 5, 4]);
|
||||
Vertex[][] edges =
|
||||
[
|
||||
[v[0], v[1]],
|
||||
[v[0], v[3]],
|
||||
[v[1], v[2]],
|
||||
[v[2], v[3]],
|
||||
[v[2], v[4]],
|
||||
[v[3], v[4]]
|
||||
];
|
||||
GraphAdjList graph = new(edges);
|
||||
Console.WriteLine("\n初始化後,圖為");
|
||||
graph.Print();
|
||||
|
||||
/* 新增邊 */
|
||||
// 頂點 1, 2 即 v[0], v[2]
|
||||
graph.AddEdge(v[0], v[2]);
|
||||
Console.WriteLine("\n新增邊 1-2 後,圖為");
|
||||
graph.Print();
|
||||
|
||||
/* 刪除邊 */
|
||||
// 頂點 1, 3 即 v[0], v[1]
|
||||
graph.RemoveEdge(v[0], v[1]);
|
||||
Console.WriteLine("\n刪除邊 1-3 後,圖為");
|
||||
graph.Print();
|
||||
|
||||
/* 新增頂點 */
|
||||
Vertex v5 = new(6);
|
||||
graph.AddVertex(v5);
|
||||
Console.WriteLine("\n新增頂點 6 後,圖為");
|
||||
graph.Print();
|
||||
|
||||
/* 刪除頂點 */
|
||||
// 頂點 3 即 v[1]
|
||||
graph.RemoveVertex(v[1]);
|
||||
Console.WriteLine("\n刪除頂點 3 後,圖為");
|
||||
graph.Print();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
/**
|
||||
* File: graph_adjacency_matrix.cs
|
||||
* Created Time: 2023-02-06
|
||||
* Author: zjkung1123 (zjkung1123@gmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_graph;
|
||||
|
||||
/* 基於鄰接矩陣實現的無向圖類別 */
|
||||
class GraphAdjMat {
|
||||
List<int> vertices; // 頂點串列,元素代表“頂點值”,索引代表“頂點索引”
|
||||
List<List<int>> adjMat; // 鄰接矩陣,行列索引對應“頂點索引”
|
||||
|
||||
/* 建構子 */
|
||||
public GraphAdjMat(int[] vertices, int[][] edges) {
|
||||
this.vertices = [];
|
||||
this.adjMat = [];
|
||||
// 新增頂點
|
||||
foreach (int val in vertices) {
|
||||
AddVertex(val);
|
||||
}
|
||||
// 新增邊
|
||||
// 請注意,edges 元素代表頂點索引,即對應 vertices 元素索引
|
||||
foreach (int[] e in edges) {
|
||||
AddEdge(e[0], e[1]);
|
||||
}
|
||||
}
|
||||
|
||||
/* 獲取頂點數量 */
|
||||
int Size() {
|
||||
return vertices.Count;
|
||||
}
|
||||
|
||||
/* 新增頂點 */
|
||||
public void AddVertex(int val) {
|
||||
int n = Size();
|
||||
// 向頂點串列中新增新頂點的值
|
||||
vertices.Add(val);
|
||||
// 在鄰接矩陣中新增一行
|
||||
List<int> newRow = new(n);
|
||||
for (int j = 0; j < n; j++) {
|
||||
newRow.Add(0);
|
||||
}
|
||||
adjMat.Add(newRow);
|
||||
// 在鄰接矩陣中新增一列
|
||||
foreach (List<int> row in adjMat) {
|
||||
row.Add(0);
|
||||
}
|
||||
}
|
||||
|
||||
/* 刪除頂點 */
|
||||
public void RemoveVertex(int index) {
|
||||
if (index >= Size())
|
||||
throw new IndexOutOfRangeException();
|
||||
// 在頂點串列中移除索引 index 的頂點
|
||||
vertices.RemoveAt(index);
|
||||
// 在鄰接矩陣中刪除索引 index 的行
|
||||
adjMat.RemoveAt(index);
|
||||
// 在鄰接矩陣中刪除索引 index 的列
|
||||
foreach (List<int> row in adjMat) {
|
||||
row.RemoveAt(index);
|
||||
}
|
||||
}
|
||||
|
||||
/* 新增邊 */
|
||||
// 參數 i, j 對應 vertices 元素索引
|
||||
public void AddEdge(int i, int j) {
|
||||
// 索引越界與相等處理
|
||||
if (i < 0 || j < 0 || i >= Size() || j >= Size() || i == j)
|
||||
throw new IndexOutOfRangeException();
|
||||
// 在無向圖中,鄰接矩陣關於主對角線對稱,即滿足 (i, j) == (j, i)
|
||||
adjMat[i][j] = 1;
|
||||
adjMat[j][i] = 1;
|
||||
}
|
||||
|
||||
/* 刪除邊 */
|
||||
// 參數 i, j 對應 vertices 元素索引
|
||||
public void RemoveEdge(int i, int j) {
|
||||
// 索引越界與相等處理
|
||||
if (i < 0 || j < 0 || i >= Size() || j >= Size() || i == j)
|
||||
throw new IndexOutOfRangeException();
|
||||
adjMat[i][j] = 0;
|
||||
adjMat[j][i] = 0;
|
||||
}
|
||||
|
||||
/* 列印鄰接矩陣 */
|
||||
public void Print() {
|
||||
Console.Write("頂點串列 = ");
|
||||
PrintUtil.PrintList(vertices);
|
||||
Console.WriteLine("鄰接矩陣 =");
|
||||
PrintUtil.PrintMatrix(adjMat);
|
||||
}
|
||||
}
|
||||
|
||||
public class graph_adjacency_matrix {
|
||||
[Test]
|
||||
public void Test() {
|
||||
/* 初始化無向圖 */
|
||||
// 請注意,edges 元素代表頂點索引,即對應 vertices 元素索引
|
||||
int[] vertices = [1, 3, 2, 5, 4];
|
||||
int[][] edges =
|
||||
[
|
||||
[0, 1],
|
||||
[0, 3],
|
||||
[1, 2],
|
||||
[2, 3],
|
||||
[2, 4],
|
||||
[3, 4]
|
||||
];
|
||||
GraphAdjMat graph = new(vertices, edges);
|
||||
Console.WriteLine("\n初始化後,圖為");
|
||||
graph.Print();
|
||||
|
||||
/* 新增邊 */
|
||||
// 頂點 1, 2 的索引分別為 0, 2
|
||||
graph.AddEdge(0, 2);
|
||||
Console.WriteLine("\n新增邊 1-2 後,圖為");
|
||||
graph.Print();
|
||||
|
||||
/* 刪除邊 */
|
||||
// 頂點 1, 3 的索引分別為 0, 1
|
||||
graph.RemoveEdge(0, 1);
|
||||
Console.WriteLine("\n刪除邊 1-3 後,圖為");
|
||||
graph.Print();
|
||||
|
||||
/* 新增頂點 */
|
||||
graph.AddVertex(6);
|
||||
Console.WriteLine("\n新增頂點 6 後,圖為");
|
||||
graph.Print();
|
||||
|
||||
/* 刪除頂點 */
|
||||
// 頂點 3 的索引為 1
|
||||
graph.RemoveVertex(1);
|
||||
Console.WriteLine("\n刪除頂點 3 後,圖為");
|
||||
graph.Print();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* File: graph_bfs.cs
|
||||
* Created Time: 2023-03-08
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_graph;
|
||||
|
||||
public class graph_bfs {
|
||||
/* 廣度優先走訪 */
|
||||
// 使用鄰接表來表示圖,以便獲取指定頂點的所有鄰接頂點
|
||||
List<Vertex> GraphBFS(GraphAdjList graph, Vertex startVet) {
|
||||
// 頂點走訪序列
|
||||
List<Vertex> res = [];
|
||||
// 雜湊表,用於記錄已被訪問過的頂點
|
||||
HashSet<Vertex> visited = [startVet];
|
||||
// 佇列用於實現 BFS
|
||||
Queue<Vertex> que = new();
|
||||
que.Enqueue(startVet);
|
||||
// 以頂點 vet 為起點,迴圈直至訪問完所有頂點
|
||||
while (que.Count > 0) {
|
||||
Vertex vet = que.Dequeue(); // 佇列首頂點出隊
|
||||
res.Add(vet); // 記錄訪問頂點
|
||||
foreach (Vertex adjVet in graph.adjList[vet]) {
|
||||
if (visited.Contains(adjVet)) {
|
||||
continue; // 跳過已被訪問的頂點
|
||||
}
|
||||
que.Enqueue(adjVet); // 只入列未訪問的頂點
|
||||
visited.Add(adjVet); // 標記該頂點已被訪問
|
||||
}
|
||||
}
|
||||
|
||||
// 返回頂點走訪序列
|
||||
return res;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
/* 初始化無向圖 */
|
||||
Vertex[] v = Vertex.ValsToVets([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
|
||||
Vertex[][] edges =
|
||||
[
|
||||
[v[0], v[1]], [v[0], v[3]], [v[1], v[2]],
|
||||
[v[1], v[4]], [v[2], v[5]], [v[3], v[4]],
|
||||
[v[3], v[6]], [v[4], v[5]], [v[4], v[7]],
|
||||
[v[5], v[8]], [v[6], v[7]], [v[7], v[8]]
|
||||
];
|
||||
|
||||
GraphAdjList graph = new(edges);
|
||||
Console.WriteLine("\n初始化後,圖為");
|
||||
graph.Print();
|
||||
|
||||
/* 廣度優先走訪 */
|
||||
List<Vertex> res = GraphBFS(graph, v[0]);
|
||||
Console.WriteLine("\n廣度優先走訪(BFS)頂點序列為");
|
||||
Console.WriteLine(string.Join(" ", Vertex.VetsToVals(res)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* File: graph_dfs.cs
|
||||
* Created Time: 2023-03-08
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_graph;
|
||||
|
||||
public class graph_dfs {
|
||||
/* 深度優先走訪輔助函式 */
|
||||
void DFS(GraphAdjList graph, HashSet<Vertex> visited, List<Vertex> res, Vertex vet) {
|
||||
res.Add(vet); // 記錄訪問頂點
|
||||
visited.Add(vet); // 標記該頂點已被訪問
|
||||
// 走訪該頂點的所有鄰接頂點
|
||||
foreach (Vertex adjVet in graph.adjList[vet]) {
|
||||
if (visited.Contains(adjVet)) {
|
||||
continue; // 跳過已被訪問的頂點
|
||||
}
|
||||
// 遞迴訪問鄰接頂點
|
||||
DFS(graph, visited, res, adjVet);
|
||||
}
|
||||
}
|
||||
|
||||
/* 深度優先走訪 */
|
||||
// 使用鄰接表來表示圖,以便獲取指定頂點的所有鄰接頂點
|
||||
List<Vertex> GraphDFS(GraphAdjList graph, Vertex startVet) {
|
||||
// 頂點走訪序列
|
||||
List<Vertex> res = [];
|
||||
// 雜湊表,用於記錄已被訪問過的頂點
|
||||
HashSet<Vertex> visited = [];
|
||||
DFS(graph, visited, res, startVet);
|
||||
return res;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
/* 初始化無向圖 */
|
||||
Vertex[] v = Vertex.ValsToVets([0, 1, 2, 3, 4, 5, 6]);
|
||||
Vertex[][] edges =
|
||||
[
|
||||
[v[0], v[1]], [v[0], v[3]], [v[1], v[2]],
|
||||
[v[2], v[5]], [v[4], v[5]], [v[5], v[6]],
|
||||
];
|
||||
|
||||
GraphAdjList graph = new(edges);
|
||||
Console.WriteLine("\n初始化後,圖為");
|
||||
graph.Print();
|
||||
|
||||
/* 深度優先走訪 */
|
||||
List<Vertex> res = GraphDFS(graph, v[0]);
|
||||
Console.WriteLine("\n深度優先走訪(DFS)頂點序列為");
|
||||
Console.WriteLine(string.Join(" ", Vertex.VetsToVals(res)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* File: coin_change_greedy.cs
|
||||
* Created Time: 2023-07-21
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_greedy;
|
||||
|
||||
public class coin_change_greedy {
|
||||
/* 零錢兌換:貪婪 */
|
||||
int CoinChangeGreedy(int[] coins, int amt) {
|
||||
// 假設 coins 串列有序
|
||||
int i = coins.Length - 1;
|
||||
int count = 0;
|
||||
// 迴圈進行貪婪選擇,直到無剩餘金額
|
||||
while (amt > 0) {
|
||||
// 找到小於且最接近剩餘金額的硬幣
|
||||
while (i > 0 && coins[i] > amt) {
|
||||
i--;
|
||||
}
|
||||
// 選擇 coins[i]
|
||||
amt -= coins[i];
|
||||
count++;
|
||||
}
|
||||
// 若未找到可行方案,則返回 -1
|
||||
return amt == 0 ? count : -1;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
// 貪婪:能夠保證找到全域性最優解
|
||||
int[] coins = [1, 5, 10, 20, 50, 100];
|
||||
int amt = 186;
|
||||
int res = CoinChangeGreedy(coins, amt);
|
||||
Console.WriteLine("\ncoins = " + coins.PrintList() + ", amt = " + amt);
|
||||
Console.WriteLine("湊到 " + amt + " 所需的最少硬幣數量為 " + res);
|
||||
|
||||
// 貪婪:無法保證找到全域性最優解
|
||||
coins = [1, 20, 50];
|
||||
amt = 60;
|
||||
res = CoinChangeGreedy(coins, amt);
|
||||
Console.WriteLine("\ncoins = " + coins.PrintList() + ", amt = " + amt);
|
||||
Console.WriteLine("湊到 " + amt + " 所需的最少硬幣數量為 " + res);
|
||||
Console.WriteLine("實際上需要的最少數量為 3 ,即 20 + 20 + 20");
|
||||
|
||||
// 貪婪:無法保證找到全域性最優解
|
||||
coins = [1, 49, 50];
|
||||
amt = 98;
|
||||
res = CoinChangeGreedy(coins, amt);
|
||||
Console.WriteLine("\ncoins = " + coins.PrintList() + ", amt = " + amt);
|
||||
Console.WriteLine("湊到 " + amt + " 所需的最少硬幣數量為 " + res);
|
||||
Console.WriteLine("實際上需要的最少數量為 2 ,即 49 + 49");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* File: fractional_knapsack.cs
|
||||
* Created Time: 2023-07-21
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_greedy;
|
||||
|
||||
/* 物品 */
|
||||
class Item(int w, int v) {
|
||||
public int w = w; // 物品重量
|
||||
public int v = v; // 物品價值
|
||||
}
|
||||
|
||||
public class fractional_knapsack {
|
||||
/* 分數背包:貪婪 */
|
||||
double FractionalKnapsack(int[] wgt, int[] val, int cap) {
|
||||
// 建立物品串列,包含兩個屬性:重量、價值
|
||||
Item[] items = new Item[wgt.Length];
|
||||
for (int i = 0; i < wgt.Length; i++) {
|
||||
items[i] = new Item(wgt[i], val[i]);
|
||||
}
|
||||
// 按照單位價值 item.v / item.w 從高到低進行排序
|
||||
Array.Sort(items, (x, y) => (y.v / y.w).CompareTo(x.v / x.w));
|
||||
// 迴圈貪婪選擇
|
||||
double res = 0;
|
||||
foreach (Item item in items) {
|
||||
if (item.w <= cap) {
|
||||
// 若剩餘容量充足,則將當前物品整個裝進背包
|
||||
res += item.v;
|
||||
cap -= item.w;
|
||||
} else {
|
||||
// 若剩餘容量不足,則將當前物品的一部分裝進背包
|
||||
res += (double)item.v / item.w * cap;
|
||||
// 已無剩餘容量,因此跳出迴圈
|
||||
break;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int[] wgt = [10, 20, 30, 40, 50];
|
||||
int[] val = [50, 120, 150, 210, 240];
|
||||
int cap = 50;
|
||||
|
||||
// 貪婪演算法
|
||||
double res = FractionalKnapsack(wgt, val, cap);
|
||||
Console.WriteLine("不超過背包容量的最大物品價值為 " + res);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* File: max_capacity.cs
|
||||
* Created Time: 2023-07-21
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_greedy;
|
||||
|
||||
public class max_capacity {
|
||||
/* 最大容量:貪婪 */
|
||||
int MaxCapacity(int[] ht) {
|
||||
// 初始化 i, j,使其分列陣列兩端
|
||||
int i = 0, j = ht.Length - 1;
|
||||
// 初始最大容量為 0
|
||||
int res = 0;
|
||||
// 迴圈貪婪選擇,直至兩板相遇
|
||||
while (i < j) {
|
||||
// 更新最大容量
|
||||
int cap = Math.Min(ht[i], ht[j]) * (j - i);
|
||||
res = Math.Max(res, cap);
|
||||
// 向內移動短板
|
||||
if (ht[i] < ht[j]) {
|
||||
i++;
|
||||
} else {
|
||||
j--;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int[] ht = [3, 8, 5, 2, 7, 7, 3, 4];
|
||||
|
||||
// 貪婪演算法
|
||||
int res = MaxCapacity(ht);
|
||||
Console.WriteLine("最大容量為 " + res);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* File: max_product_cutting.cs
|
||||
* Created Time: 2023-07-21
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_greedy;
|
||||
|
||||
public class max_product_cutting {
|
||||
/* 最大切分乘積:貪婪 */
|
||||
int MaxProductCutting(int n) {
|
||||
// 當 n <= 3 時,必須切分出一個 1
|
||||
if (n <= 3) {
|
||||
return 1 * (n - 1);
|
||||
}
|
||||
// 貪婪地切分出 3 ,a 為 3 的個數,b 為餘數
|
||||
int a = n / 3;
|
||||
int b = n % 3;
|
||||
if (b == 1) {
|
||||
// 當餘數為 1 時,將一對 1 * 3 轉化為 2 * 2
|
||||
return (int)Math.Pow(3, a - 1) * 2 * 2;
|
||||
}
|
||||
if (b == 2) {
|
||||
// 當餘數為 2 時,不做處理
|
||||
return (int)Math.Pow(3, a) * 2;
|
||||
}
|
||||
// 當餘數為 0 時,不做處理
|
||||
return (int)Math.Pow(3, a);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int n = 58;
|
||||
|
||||
// 貪婪演算法
|
||||
int res = MaxProductCutting(n);
|
||||
Console.WriteLine("最大切分乘積為" + res);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* File: array_hash_map.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_hashing;
|
||||
|
||||
/* 鍵值對 int->string */
|
||||
class Pair(int key, string val) {
|
||||
public int key = key;
|
||||
public string val = val;
|
||||
}
|
||||
|
||||
/* 基於陣列實現的雜湊表 */
|
||||
class ArrayHashMap {
|
||||
List<Pair?> buckets;
|
||||
public ArrayHashMap() {
|
||||
// 初始化陣列,包含 100 個桶
|
||||
buckets = [];
|
||||
for (int i = 0; i < 100; i++) {
|
||||
buckets.Add(null);
|
||||
}
|
||||
}
|
||||
|
||||
/* 雜湊函式 */
|
||||
int HashFunc(int key) {
|
||||
int index = key % 100;
|
||||
return index;
|
||||
}
|
||||
|
||||
/* 查詢操作 */
|
||||
public string? Get(int key) {
|
||||
int index = HashFunc(key);
|
||||
Pair? pair = buckets[index];
|
||||
if (pair == null) return null;
|
||||
return pair.val;
|
||||
}
|
||||
|
||||
/* 新增操作 */
|
||||
public void Put(int key, string val) {
|
||||
Pair pair = new(key, val);
|
||||
int index = HashFunc(key);
|
||||
buckets[index] = pair;
|
||||
}
|
||||
|
||||
/* 刪除操作 */
|
||||
public void Remove(int key) {
|
||||
int index = HashFunc(key);
|
||||
// 置為 null ,代表刪除
|
||||
buckets[index] = null;
|
||||
}
|
||||
|
||||
/* 獲取所有鍵值對 */
|
||||
public List<Pair> PairSet() {
|
||||
List<Pair> pairSet = [];
|
||||
foreach (Pair? pair in buckets) {
|
||||
if (pair != null)
|
||||
pairSet.Add(pair);
|
||||
}
|
||||
return pairSet;
|
||||
}
|
||||
|
||||
/* 獲取所有鍵 */
|
||||
public List<int> KeySet() {
|
||||
List<int> keySet = [];
|
||||
foreach (Pair? pair in buckets) {
|
||||
if (pair != null)
|
||||
keySet.Add(pair.key);
|
||||
}
|
||||
return keySet;
|
||||
}
|
||||
|
||||
/* 獲取所有值 */
|
||||
public List<string> ValueSet() {
|
||||
List<string> valueSet = [];
|
||||
foreach (Pair? pair in buckets) {
|
||||
if (pair != null)
|
||||
valueSet.Add(pair.val);
|
||||
}
|
||||
return valueSet;
|
||||
}
|
||||
|
||||
/* 列印雜湊表 */
|
||||
public void Print() {
|
||||
foreach (Pair kv in PairSet()) {
|
||||
Console.WriteLine(kv.key + " -> " + kv.val);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public class array_hash_map {
|
||||
[Test]
|
||||
public void Test() {
|
||||
/* 初始化雜湊表 */
|
||||
ArrayHashMap map = new();
|
||||
|
||||
/* 新增操作 */
|
||||
// 在雜湊表中新增鍵值對 (key, value)
|
||||
map.Put(12836, "小哈");
|
||||
map.Put(15937, "小囉");
|
||||
map.Put(16750, "小算");
|
||||
map.Put(13276, "小法");
|
||||
map.Put(10583, "小鴨");
|
||||
Console.WriteLine("\n新增完成後,雜湊表為\nKey -> Value");
|
||||
map.Print();
|
||||
|
||||
/* 查詢操作 */
|
||||
// 向雜湊表中輸入鍵 key ,得到值 value
|
||||
string? name = map.Get(15937);
|
||||
Console.WriteLine("\n輸入學號 15937 ,查詢到姓名 " + name);
|
||||
|
||||
/* 刪除操作 */
|
||||
// 在雜湊表中刪除鍵值對 (key, value)
|
||||
map.Remove(10583);
|
||||
Console.WriteLine("\n刪除 10583 後,雜湊表為\nKey -> Value");
|
||||
map.Print();
|
||||
|
||||
/* 走訪雜湊表 */
|
||||
Console.WriteLine("\n走訪鍵值對 Key->Value");
|
||||
foreach (Pair kv in map.PairSet()) {
|
||||
Console.WriteLine(kv.key + " -> " + kv.val);
|
||||
}
|
||||
Console.WriteLine("\n單獨走訪鍵 Key");
|
||||
foreach (int key in map.KeySet()) {
|
||||
Console.WriteLine(key);
|
||||
}
|
||||
Console.WriteLine("\n單獨走訪值 Value");
|
||||
foreach (string val in map.ValueSet()) {
|
||||
Console.WriteLine(val);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* File: built_in_hash.cs
|
||||
* Created Time: 2023-06-26
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_hashing;
|
||||
|
||||
public class built_in_hash {
|
||||
[Test]
|
||||
public void Test() {
|
||||
int num = 3;
|
||||
int hashNum = num.GetHashCode();
|
||||
Console.WriteLine("整數 " + num + " 的雜湊值為 " + hashNum);
|
||||
|
||||
bool bol = true;
|
||||
int hashBol = bol.GetHashCode();
|
||||
Console.WriteLine("布林量 " + bol + " 的雜湊值為 " + hashBol);
|
||||
|
||||
double dec = 3.14159;
|
||||
int hashDec = dec.GetHashCode();
|
||||
Console.WriteLine("小數 " + dec + " 的雜湊值為 " + hashDec);
|
||||
|
||||
string str = "Hello 演算法";
|
||||
int hashStr = str.GetHashCode();
|
||||
Console.WriteLine("字串 " + str + " 的雜湊值為 " + hashStr);
|
||||
|
||||
object[] arr = [12836, "小哈"];
|
||||
int hashTup = arr.GetHashCode();
|
||||
Console.WriteLine("陣列 [" + string.Join(", ", arr) + "] 的雜湊值為 " + hashTup);
|
||||
|
||||
ListNode obj = new(0);
|
||||
int hashObj = obj.GetHashCode();
|
||||
Console.WriteLine("節點物件 " + obj + " 的雜湊值為 " + hashObj);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
|
||||
/**
|
||||
* File: hash_map.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_hashing;
|
||||
|
||||
public class hash_map {
|
||||
[Test]
|
||||
public void Test() {
|
||||
/* 初始化雜湊表 */
|
||||
Dictionary<int, string> map = new() {
|
||||
/* 新增操作 */
|
||||
// 在雜湊表中新增鍵值對 (key, value)
|
||||
{ 12836, "小哈" },
|
||||
{ 15937, "小囉" },
|
||||
{ 16750, "小算" },
|
||||
{ 13276, "小法" },
|
||||
{ 10583, "小鴨" }
|
||||
};
|
||||
Console.WriteLine("\n新增完成後,雜湊表為\nKey -> Value");
|
||||
PrintUtil.PrintHashMap(map);
|
||||
|
||||
/* 查詢操作 */
|
||||
// 向雜湊表中輸入鍵 key ,得到值 value
|
||||
string name = map[15937];
|
||||
Console.WriteLine("\n輸入學號 15937 ,查詢到姓名 " + name);
|
||||
|
||||
/* 刪除操作 */
|
||||
// 在雜湊表中刪除鍵值對 (key, value)
|
||||
map.Remove(10583);
|
||||
Console.WriteLine("\n刪除 10583 後,雜湊表為\nKey -> Value");
|
||||
PrintUtil.PrintHashMap(map);
|
||||
|
||||
/* 走訪雜湊表 */
|
||||
Console.WriteLine("\n走訪鍵值對 Key->Value");
|
||||
foreach (var kv in map) {
|
||||
Console.WriteLine(kv.Key + " -> " + kv.Value);
|
||||
}
|
||||
Console.WriteLine("\n單獨走訪鍵 Key");
|
||||
foreach (int key in map.Keys) {
|
||||
Console.WriteLine(key);
|
||||
}
|
||||
Console.WriteLine("\n單獨走訪值 Value");
|
||||
foreach (string val in map.Values) {
|
||||
Console.WriteLine(val);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
/**
|
||||
* File: hash_map_chaining.cs
|
||||
* Created Time: 2023-06-26
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_hashing;
|
||||
|
||||
/* 鏈式位址雜湊表 */
|
||||
class HashMapChaining {
|
||||
int size; // 鍵值對數量
|
||||
int capacity; // 雜湊表容量
|
||||
double loadThres; // 觸發擴容的負載因子閾值
|
||||
int extendRatio; // 擴容倍數
|
||||
List<List<Pair>> buckets; // 桶陣列
|
||||
|
||||
/* 建構子 */
|
||||
public HashMapChaining() {
|
||||
size = 0;
|
||||
capacity = 4;
|
||||
loadThres = 2.0 / 3.0;
|
||||
extendRatio = 2;
|
||||
buckets = new List<List<Pair>>(capacity);
|
||||
for (int i = 0; i < capacity; i++) {
|
||||
buckets.Add([]);
|
||||
}
|
||||
}
|
||||
|
||||
/* 雜湊函式 */
|
||||
int HashFunc(int key) {
|
||||
return key % capacity;
|
||||
}
|
||||
|
||||
/* 負載因子 */
|
||||
double LoadFactor() {
|
||||
return (double)size / capacity;
|
||||
}
|
||||
|
||||
/* 查詢操作 */
|
||||
public string? Get(int key) {
|
||||
int index = HashFunc(key);
|
||||
// 走訪桶,若找到 key ,則返回對應 val
|
||||
foreach (Pair pair in buckets[index]) {
|
||||
if (pair.key == key) {
|
||||
return pair.val;
|
||||
}
|
||||
}
|
||||
// 若未找到 key ,則返回 null
|
||||
return null;
|
||||
}
|
||||
|
||||
/* 新增操作 */
|
||||
public void Put(int key, string val) {
|
||||
// 當負載因子超過閾值時,執行擴容
|
||||
if (LoadFactor() > loadThres) {
|
||||
Extend();
|
||||
}
|
||||
int index = HashFunc(key);
|
||||
// 走訪桶,若遇到指定 key ,則更新對應 val 並返回
|
||||
foreach (Pair pair in buckets[index]) {
|
||||
if (pair.key == key) {
|
||||
pair.val = val;
|
||||
return;
|
||||
}
|
||||
}
|
||||
// 若無該 key ,則將鍵值對新增至尾部
|
||||
buckets[index].Add(new Pair(key, val));
|
||||
size++;
|
||||
}
|
||||
|
||||
/* 刪除操作 */
|
||||
public void Remove(int key) {
|
||||
int index = HashFunc(key);
|
||||
// 走訪桶,從中刪除鍵值對
|
||||
foreach (Pair pair in buckets[index].ToList()) {
|
||||
if (pair.key == key) {
|
||||
buckets[index].Remove(pair);
|
||||
size--;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 擴容雜湊表 */
|
||||
void Extend() {
|
||||
// 暫存原雜湊表
|
||||
List<List<Pair>> bucketsTmp = buckets;
|
||||
// 初始化擴容後的新雜湊表
|
||||
capacity *= extendRatio;
|
||||
buckets = new List<List<Pair>>(capacity);
|
||||
for (int i = 0; i < capacity; i++) {
|
||||
buckets.Add([]);
|
||||
}
|
||||
size = 0;
|
||||
// 將鍵值對從原雜湊表搬運至新雜湊表
|
||||
foreach (List<Pair> bucket in bucketsTmp) {
|
||||
foreach (Pair pair in bucket) {
|
||||
Put(pair.key, pair.val);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 列印雜湊表 */
|
||||
public void Print() {
|
||||
foreach (List<Pair> bucket in buckets) {
|
||||
List<string> res = [];
|
||||
foreach (Pair pair in bucket) {
|
||||
res.Add(pair.key + " -> " + pair.val);
|
||||
}
|
||||
foreach (string kv in res) {
|
||||
Console.WriteLine(kv);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class hash_map_chaining {
|
||||
[Test]
|
||||
public void Test() {
|
||||
/* 初始化雜湊表 */
|
||||
HashMapChaining map = new();
|
||||
|
||||
/* 新增操作 */
|
||||
// 在雜湊表中新增鍵值對 (key, value)
|
||||
map.Put(12836, "小哈");
|
||||
map.Put(15937, "小囉");
|
||||
map.Put(16750, "小算");
|
||||
map.Put(13276, "小法");
|
||||
map.Put(10583, "小鴨");
|
||||
Console.WriteLine("\n新增完成後,雜湊表為\nKey -> Value");
|
||||
map.Print();
|
||||
|
||||
/* 查詢操作 */
|
||||
// 向雜湊表中輸入鍵 key ,得到值 value
|
||||
string? name = map.Get(13276);
|
||||
Console.WriteLine("\n輸入學號 13276 ,查詢到姓名 " + name);
|
||||
|
||||
/* 刪除操作 */
|
||||
// 在雜湊表中刪除鍵值對 (key, value)
|
||||
map.Remove(12836);
|
||||
Console.WriteLine("\n刪除 12836 後,雜湊表為\nKey -> Value");
|
||||
map.Print();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
/**
|
||||
* File: hash_map_open_addressing.cs
|
||||
* Created Time: 2023-06-26
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_hashing;
|
||||
|
||||
/* 開放定址雜湊表 */
|
||||
class HashMapOpenAddressing {
|
||||
int size; // 鍵值對數量
|
||||
int capacity = 4; // 雜湊表容量
|
||||
double loadThres = 2.0 / 3.0; // 觸發擴容的負載因子閾值
|
||||
int extendRatio = 2; // 擴容倍數
|
||||
Pair[] buckets; // 桶陣列
|
||||
Pair TOMBSTONE = new(-1, "-1"); // 刪除標記
|
||||
|
||||
/* 建構子 */
|
||||
public HashMapOpenAddressing() {
|
||||
size = 0;
|
||||
buckets = new Pair[capacity];
|
||||
}
|
||||
|
||||
/* 雜湊函式 */
|
||||
int HashFunc(int key) {
|
||||
return key % capacity;
|
||||
}
|
||||
|
||||
/* 負載因子 */
|
||||
double LoadFactor() {
|
||||
return (double)size / capacity;
|
||||
}
|
||||
|
||||
/* 搜尋 key 對應的桶索引 */
|
||||
int FindBucket(int key) {
|
||||
int index = HashFunc(key);
|
||||
int firstTombstone = -1;
|
||||
// 線性探查,當遇到空桶時跳出
|
||||
while (buckets[index] != null) {
|
||||
// 若遇到 key ,返回對應的桶索引
|
||||
if (buckets[index].key == key) {
|
||||
// 若之前遇到了刪除標記,則將鍵值對移動至該索引處
|
||||
if (firstTombstone != -1) {
|
||||
buckets[firstTombstone] = buckets[index];
|
||||
buckets[index] = TOMBSTONE;
|
||||
return firstTombstone; // 返回移動後的桶索引
|
||||
}
|
||||
return index; // 返回桶索引
|
||||
}
|
||||
// 記錄遇到的首個刪除標記
|
||||
if (firstTombstone == -1 && buckets[index] == TOMBSTONE) {
|
||||
firstTombstone = index;
|
||||
}
|
||||
// 計算桶索引,越過尾部則返回頭部
|
||||
index = (index + 1) % capacity;
|
||||
}
|
||||
// 若 key 不存在,則返回新增點的索引
|
||||
return firstTombstone == -1 ? index : firstTombstone;
|
||||
}
|
||||
|
||||
/* 查詢操作 */
|
||||
public string? Get(int key) {
|
||||
// 搜尋 key 對應的桶索引
|
||||
int index = FindBucket(key);
|
||||
// 若找到鍵值對,則返回對應 val
|
||||
if (buckets[index] != null && buckets[index] != TOMBSTONE) {
|
||||
return buckets[index].val;
|
||||
}
|
||||
// 若鍵值對不存在,則返回 null
|
||||
return null;
|
||||
}
|
||||
|
||||
/* 新增操作 */
|
||||
public void Put(int key, string val) {
|
||||
// 當負載因子超過閾值時,執行擴容
|
||||
if (LoadFactor() > loadThres) {
|
||||
Extend();
|
||||
}
|
||||
// 搜尋 key 對應的桶索引
|
||||
int index = FindBucket(key);
|
||||
// 若找到鍵值對,則覆蓋 val 並返回
|
||||
if (buckets[index] != null && buckets[index] != TOMBSTONE) {
|
||||
buckets[index].val = val;
|
||||
return;
|
||||
}
|
||||
// 若鍵值對不存在,則新增該鍵值對
|
||||
buckets[index] = new Pair(key, val);
|
||||
size++;
|
||||
}
|
||||
|
||||
/* 刪除操作 */
|
||||
public void Remove(int key) {
|
||||
// 搜尋 key 對應的桶索引
|
||||
int index = FindBucket(key);
|
||||
// 若找到鍵值對,則用刪除標記覆蓋它
|
||||
if (buckets[index] != null && buckets[index] != TOMBSTONE) {
|
||||
buckets[index] = TOMBSTONE;
|
||||
size--;
|
||||
}
|
||||
}
|
||||
|
||||
/* 擴容雜湊表 */
|
||||
void Extend() {
|
||||
// 暫存原雜湊表
|
||||
Pair[] bucketsTmp = buckets;
|
||||
// 初始化擴容後的新雜湊表
|
||||
capacity *= extendRatio;
|
||||
buckets = new Pair[capacity];
|
||||
size = 0;
|
||||
// 將鍵值對從原雜湊表搬運至新雜湊表
|
||||
foreach (Pair pair in bucketsTmp) {
|
||||
if (pair != null && pair != TOMBSTONE) {
|
||||
Put(pair.key, pair.val);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 列印雜湊表 */
|
||||
public void Print() {
|
||||
foreach (Pair pair in buckets) {
|
||||
if (pair == null) {
|
||||
Console.WriteLine("null");
|
||||
} else if (pair == TOMBSTONE) {
|
||||
Console.WriteLine("TOMBSTONE");
|
||||
} else {
|
||||
Console.WriteLine(pair.key + " -> " + pair.val);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class hash_map_open_addressing {
|
||||
[Test]
|
||||
public void Test() {
|
||||
/* 初始化雜湊表 */
|
||||
HashMapOpenAddressing map = new();
|
||||
|
||||
/* 新增操作 */
|
||||
// 在雜湊表中新增鍵值對 (key, value)
|
||||
map.Put(12836, "小哈");
|
||||
map.Put(15937, "小囉");
|
||||
map.Put(16750, "小算");
|
||||
map.Put(13276, "小法");
|
||||
map.Put(10583, "小鴨");
|
||||
Console.WriteLine("\n新增完成後,雜湊表為\nKey -> Value");
|
||||
map.Print();
|
||||
|
||||
/* 查詢操作 */
|
||||
// 向雜湊表中輸入鍵 key ,得到值 value
|
||||
string? name = map.Get(13276);
|
||||
Console.WriteLine("\n輸入學號 13276 ,查詢到姓名 " + name);
|
||||
|
||||
/* 刪除操作 */
|
||||
// 在雜湊表中刪除鍵值對 (key, value)
|
||||
map.Remove(16750);
|
||||
Console.WriteLine("\n刪除 16750 後,雜湊表為\nKey -> Value");
|
||||
map.Print();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* File: simple_hash.cs
|
||||
* Created Time: 2023-06-26
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_hashing;
|
||||
|
||||
public class simple_hash {
|
||||
/* 加法雜湊 */
|
||||
int AddHash(string key) {
|
||||
long hash = 0;
|
||||
const int MODULUS = 1000000007;
|
||||
foreach (char c in key) {
|
||||
hash = (hash + c) % MODULUS;
|
||||
}
|
||||
return (int)hash;
|
||||
}
|
||||
|
||||
/* 乘法雜湊 */
|
||||
int MulHash(string key) {
|
||||
long hash = 0;
|
||||
const int MODULUS = 1000000007;
|
||||
foreach (char c in key) {
|
||||
hash = (31 * hash + c) % MODULUS;
|
||||
}
|
||||
return (int)hash;
|
||||
}
|
||||
|
||||
/* 互斥或雜湊 */
|
||||
int XorHash(string key) {
|
||||
int hash = 0;
|
||||
const int MODULUS = 1000000007;
|
||||
foreach (char c in key) {
|
||||
hash ^= c;
|
||||
}
|
||||
return hash & MODULUS;
|
||||
}
|
||||
|
||||
/* 旋轉雜湊 */
|
||||
int RotHash(string key) {
|
||||
long hash = 0;
|
||||
const int MODULUS = 1000000007;
|
||||
foreach (char c in key) {
|
||||
hash = ((hash << 4) ^ (hash >> 28) ^ c) % MODULUS;
|
||||
}
|
||||
return (int)hash;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
string key = "Hello 演算法";
|
||||
|
||||
int hash = AddHash(key);
|
||||
Console.WriteLine("加法雜湊值為 " + hash);
|
||||
|
||||
hash = MulHash(key);
|
||||
Console.WriteLine("乘法雜湊值為 " + hash);
|
||||
|
||||
hash = XorHash(key);
|
||||
Console.WriteLine("互斥或雜湊值為 " + hash);
|
||||
|
||||
hash = RotHash(key);
|
||||
Console.WriteLine("旋轉雜湊值為 " + hash);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* File: heap.cs
|
||||
* Created Time: 2023-02-06
|
||||
* Author: zjkung1123 (zjkung1123@gmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_heap;
|
||||
|
||||
public class heap {
|
||||
void TestPush(PriorityQueue<int, int> heap, int val) {
|
||||
heap.Enqueue(val, val); // 元素入堆積
|
||||
Console.WriteLine($"\n元素 {val} 入堆積後\n");
|
||||
PrintUtil.PrintHeap(heap);
|
||||
}
|
||||
|
||||
void TestPop(PriorityQueue<int, int> heap) {
|
||||
int val = heap.Dequeue(); // 堆積頂元素出堆積
|
||||
Console.WriteLine($"\n堆積頂元素 {val} 出堆積後\n");
|
||||
PrintUtil.PrintHeap(heap);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
/* 初始化堆積 */
|
||||
// 初始化小頂堆積
|
||||
PriorityQueue<int, int> minHeap = new();
|
||||
// 初始化大頂堆積(使用 lambda 表示式修改 Comparator 即可)
|
||||
PriorityQueue<int, int> maxHeap = new(Comparer<int>.Create((x, y) => y - x));
|
||||
Console.WriteLine("以下測試樣例為大頂堆積");
|
||||
|
||||
/* 元素入堆積 */
|
||||
TestPush(maxHeap, 1);
|
||||
TestPush(maxHeap, 3);
|
||||
TestPush(maxHeap, 2);
|
||||
TestPush(maxHeap, 5);
|
||||
TestPush(maxHeap, 4);
|
||||
|
||||
/* 獲取堆積頂元素 */
|
||||
int peek = maxHeap.Peek();
|
||||
Console.WriteLine($"堆積頂元素為 {peek}");
|
||||
|
||||
/* 堆積頂元素出堆積 */
|
||||
// 出堆積元素會形成一個從大到小的序列
|
||||
TestPop(maxHeap);
|
||||
TestPop(maxHeap);
|
||||
TestPop(maxHeap);
|
||||
TestPop(maxHeap);
|
||||
TestPop(maxHeap);
|
||||
|
||||
/* 獲取堆積大小 */
|
||||
int size = maxHeap.Count;
|
||||
Console.WriteLine($"堆積元素數量為 {size}");
|
||||
|
||||
/* 判斷堆積是否為空 */
|
||||
bool isEmpty = maxHeap.Count == 0;
|
||||
Console.WriteLine($"堆積是否為空 {isEmpty}");
|
||||
|
||||
/* 輸入串列並建堆積 */
|
||||
var list = new int[] { 1, 3, 2, 5, 4 };
|
||||
minHeap = new PriorityQueue<int, int>(list.Select(x => (x, x)));
|
||||
Console.WriteLine("輸入串列並建立小頂堆積後");
|
||||
PrintUtil.PrintHeap(minHeap);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* File: my_heap.cs
|
||||
* Created Time: 2023-02-06
|
||||
* Author: zjkung1123 (zjkung1123@gmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_heap;
|
||||
|
||||
/* 大頂堆積 */
|
||||
class MaxHeap {
|
||||
// 使用串列而非陣列,這樣無須考慮擴容問題
|
||||
List<int> maxHeap;
|
||||
|
||||
/* 建構子,建立空堆積 */
|
||||
public MaxHeap() {
|
||||
maxHeap = [];
|
||||
}
|
||||
|
||||
/* 建構子,根據輸入串列建堆積 */
|
||||
public MaxHeap(IEnumerable<int> nums) {
|
||||
// 將串列元素原封不動新增進堆積
|
||||
maxHeap = new List<int>(nums);
|
||||
// 堆積化除葉節點以外的其他所有節點
|
||||
var size = Parent(this.Size() - 1);
|
||||
for (int i = size; i >= 0; i--) {
|
||||
SiftDown(i);
|
||||
}
|
||||
}
|
||||
|
||||
/* 獲取左子節點的索引 */
|
||||
int Left(int i) {
|
||||
return 2 * i + 1;
|
||||
}
|
||||
|
||||
/* 獲取右子節點的索引 */
|
||||
int Right(int i) {
|
||||
return 2 * i + 2;
|
||||
}
|
||||
|
||||
/* 獲取父節點的索引 */
|
||||
int Parent(int i) {
|
||||
return (i - 1) / 2; // 向下整除
|
||||
}
|
||||
|
||||
/* 訪問堆積頂元素 */
|
||||
public int Peek() {
|
||||
return maxHeap[0];
|
||||
}
|
||||
|
||||
/* 元素入堆積 */
|
||||
public void Push(int val) {
|
||||
// 新增節點
|
||||
maxHeap.Add(val);
|
||||
// 從底至頂堆積化
|
||||
SiftUp(Size() - 1);
|
||||
}
|
||||
|
||||
/* 獲取堆積大小 */
|
||||
public int Size() {
|
||||
return maxHeap.Count;
|
||||
}
|
||||
|
||||
/* 判斷堆積是否為空 */
|
||||
public bool IsEmpty() {
|
||||
return Size() == 0;
|
||||
}
|
||||
|
||||
/* 從節點 i 開始,從底至頂堆積化 */
|
||||
void SiftUp(int i) {
|
||||
while (true) {
|
||||
// 獲取節點 i 的父節點
|
||||
int p = Parent(i);
|
||||
// 若“越過根節點”或“節點無須修復”,則結束堆積化
|
||||
if (p < 0 || maxHeap[i] <= maxHeap[p])
|
||||
break;
|
||||
// 交換兩節點
|
||||
Swap(i, p);
|
||||
// 迴圈向上堆積化
|
||||
i = p;
|
||||
}
|
||||
}
|
||||
|
||||
/* 元素出堆積 */
|
||||
public int Pop() {
|
||||
// 判空處理
|
||||
if (IsEmpty())
|
||||
throw new IndexOutOfRangeException();
|
||||
// 交換根節點與最右葉節點(交換首元素與尾元素)
|
||||
Swap(0, Size() - 1);
|
||||
// 刪除節點
|
||||
int val = maxHeap.Last();
|
||||
maxHeap.RemoveAt(Size() - 1);
|
||||
// 從頂至底堆積化
|
||||
SiftDown(0);
|
||||
// 返回堆積頂元素
|
||||
return val;
|
||||
}
|
||||
|
||||
/* 從節點 i 開始,從頂至底堆積化 */
|
||||
void SiftDown(int i) {
|
||||
while (true) {
|
||||
// 判斷節點 i, l, r 中值最大的節點,記為 ma
|
||||
int l = Left(i), r = Right(i), ma = i;
|
||||
if (l < Size() && maxHeap[l] > maxHeap[ma])
|
||||
ma = l;
|
||||
if (r < Size() && maxHeap[r] > maxHeap[ma])
|
||||
ma = r;
|
||||
// 若“節點 i 最大”或“越過葉節點”,則結束堆積化
|
||||
if (ma == i) break;
|
||||
// 交換兩節點
|
||||
Swap(i, ma);
|
||||
// 迴圈向下堆積化
|
||||
i = ma;
|
||||
}
|
||||
}
|
||||
|
||||
/* 交換元素 */
|
||||
void Swap(int i, int p) {
|
||||
(maxHeap[i], maxHeap[p]) = (maxHeap[p], maxHeap[i]);
|
||||
}
|
||||
|
||||
/* 列印堆積(二元樹) */
|
||||
public void Print() {
|
||||
var queue = new Queue<int>(maxHeap);
|
||||
PrintUtil.PrintHeap(queue);
|
||||
}
|
||||
}
|
||||
|
||||
public class my_heap {
|
||||
[Test]
|
||||
public void Test() {
|
||||
/* 初始化大頂堆積 */
|
||||
MaxHeap maxHeap = new([9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2]);
|
||||
Console.WriteLine("\n輸入串列並建堆積後");
|
||||
maxHeap.Print();
|
||||
|
||||
/* 獲取堆積頂元素 */
|
||||
int peek = maxHeap.Peek();
|
||||
Console.WriteLine($"堆積頂元素為 {peek}");
|
||||
|
||||
/* 元素入堆積 */
|
||||
int val = 7;
|
||||
maxHeap.Push(val);
|
||||
Console.WriteLine($"元素 {val} 入堆積後");
|
||||
maxHeap.Print();
|
||||
|
||||
/* 堆積頂元素出堆積 */
|
||||
peek = maxHeap.Pop();
|
||||
Console.WriteLine($"堆積頂元素 {peek} 出堆積後");
|
||||
maxHeap.Print();
|
||||
|
||||
/* 獲取堆積大小 */
|
||||
int size = maxHeap.Size();
|
||||
Console.WriteLine($"堆積元素數量為 {size}");
|
||||
|
||||
/* 判斷堆積是否為空 */
|
||||
bool isEmpty = maxHeap.IsEmpty();
|
||||
Console.WriteLine($"堆積是否為空 {isEmpty}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* File: top_k.cs
|
||||
* Created Time: 2023-06-14
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_heap;
|
||||
|
||||
public class top_k {
|
||||
/* 基於堆積查詢陣列中最大的 k 個元素 */
|
||||
PriorityQueue<int, int> TopKHeap(int[] nums, int k) {
|
||||
// 初始化小頂堆積
|
||||
PriorityQueue<int, int> heap = new();
|
||||
// 將陣列的前 k 個元素入堆積
|
||||
for (int i = 0; i < k; i++) {
|
||||
heap.Enqueue(nums[i], nums[i]);
|
||||
}
|
||||
// 從第 k+1 個元素開始,保持堆積的長度為 k
|
||||
for (int i = k; i < nums.Length; i++) {
|
||||
// 若當前元素大於堆積頂元素,則將堆積頂元素出堆積、當前元素入堆積
|
||||
if (nums[i] > heap.Peek()) {
|
||||
heap.Dequeue();
|
||||
heap.Enqueue(nums[i], nums[i]);
|
||||
}
|
||||
}
|
||||
return heap;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int[] nums = [1, 7, 6, 3, 2];
|
||||
int k = 3;
|
||||
PriorityQueue<int, int> res = TopKHeap(nums, k);
|
||||
Console.WriteLine("最大的 " + k + " 個元素為");
|
||||
PrintUtil.PrintHeap(res);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* File: binary_search.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_searching;
|
||||
|
||||
public class binary_search {
|
||||
/* 二分搜尋(雙閉區間) */
|
||||
int BinarySearch(int[] nums, int target) {
|
||||
// 初始化雙閉區間 [0, n-1] ,即 i, j 分別指向陣列首元素、尾元素
|
||||
int i = 0, j = nums.Length - 1;
|
||||
// 迴圈,當搜尋區間為空時跳出(當 i > j 時為空)
|
||||
while (i <= j) {
|
||||
int m = i + (j - i) / 2; // 計算中點索引 m
|
||||
if (nums[m] < target) // 此情況說明 target 在區間 [m+1, j] 中
|
||||
i = m + 1;
|
||||
else if (nums[m] > target) // 此情況說明 target 在區間 [i, m-1] 中
|
||||
j = m - 1;
|
||||
else // 找到目標元素,返回其索引
|
||||
return m;
|
||||
}
|
||||
// 未找到目標元素,返回 -1
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* 二分搜尋(左閉右開區間) */
|
||||
int BinarySearchLCRO(int[] nums, int target) {
|
||||
// 初始化左閉右開區間 [0, n) ,即 i, j 分別指向陣列首元素、尾元素+1
|
||||
int i = 0, j = nums.Length;
|
||||
// 迴圈,當搜尋區間為空時跳出(當 i = j 時為空)
|
||||
while (i < j) {
|
||||
int m = i + (j - i) / 2; // 計算中點索引 m
|
||||
if (nums[m] < target) // 此情況說明 target 在區間 [m+1, j) 中
|
||||
i = m + 1;
|
||||
else if (nums[m] > target) // 此情況說明 target 在區間 [i, m) 中
|
||||
j = m;
|
||||
else // 找到目標元素,返回其索引
|
||||
return m;
|
||||
}
|
||||
// 未找到目標元素,返回 -1
|
||||
return -1;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int target = 6;
|
||||
int[] nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35];
|
||||
|
||||
/* 二分搜尋(雙閉區間) */
|
||||
int index = BinarySearch(nums, target);
|
||||
Console.WriteLine("目標元素 6 的索引 = " + index);
|
||||
|
||||
/* 二分搜尋(左閉右開區間) */
|
||||
index = BinarySearchLCRO(nums, target);
|
||||
Console.WriteLine("目標元素 6 的索引 = " + index);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* File: binary_search_edge.cs
|
||||
* Created Time: 2023-08-06
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_searching;
|
||||
|
||||
public class binary_search_edge {
|
||||
/* 二分搜尋最左一個 target */
|
||||
int BinarySearchLeftEdge(int[] nums, int target) {
|
||||
// 等價於查詢 target 的插入點
|
||||
int i = binary_search_insertion.BinarySearchInsertion(nums, target);
|
||||
// 未找到 target ,返回 -1
|
||||
if (i == nums.Length || nums[i] != target) {
|
||||
return -1;
|
||||
}
|
||||
// 找到 target ,返回索引 i
|
||||
return i;
|
||||
}
|
||||
|
||||
/* 二分搜尋最右一個 target */
|
||||
int BinarySearchRightEdge(int[] nums, int target) {
|
||||
// 轉化為查詢最左一個 target + 1
|
||||
int i = binary_search_insertion.BinarySearchInsertion(nums, target + 1);
|
||||
// j 指向最右一個 target ,i 指向首個大於 target 的元素
|
||||
int j = i - 1;
|
||||
// 未找到 target ,返回 -1
|
||||
if (j == -1 || nums[j] != target) {
|
||||
return -1;
|
||||
}
|
||||
// 找到 target ,返回索引 j
|
||||
return j;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
// 包含重複元素的陣列
|
||||
int[] nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15];
|
||||
Console.WriteLine("\n陣列 nums = " + nums.PrintList());
|
||||
|
||||
// 二分搜尋左邊界和右邊界
|
||||
foreach (int target in new int[] { 6, 7 }) {
|
||||
int index = BinarySearchLeftEdge(nums, target);
|
||||
Console.WriteLine("最左一個元素 " + target + " 的索引為 " + index);
|
||||
index = BinarySearchRightEdge(nums, target);
|
||||
Console.WriteLine("最右一個元素 " + target + " 的索引為 " + index);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* File: binary_search_insertion.cs
|
||||
* Created Time: 2023-08-06
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_searching;
|
||||
|
||||
public class binary_search_insertion {
|
||||
/* 二分搜尋插入點(無重複元素) */
|
||||
public static int BinarySearchInsertionSimple(int[] nums, int target) {
|
||||
int i = 0, j = nums.Length - 1; // 初始化雙閉區間 [0, n-1]
|
||||
while (i <= j) {
|
||||
int m = i + (j - i) / 2; // 計算中點索引 m
|
||||
if (nums[m] < target) {
|
||||
i = m + 1; // target 在區間 [m+1, j] 中
|
||||
} else if (nums[m] > target) {
|
||||
j = m - 1; // target 在區間 [i, m-1] 中
|
||||
} else {
|
||||
return m; // 找到 target ,返回插入點 m
|
||||
}
|
||||
}
|
||||
// 未找到 target ,返回插入點 i
|
||||
return i;
|
||||
}
|
||||
|
||||
/* 二分搜尋插入點(存在重複元素) */
|
||||
public static int BinarySearchInsertion(int[] nums, int target) {
|
||||
int i = 0, j = nums.Length - 1; // 初始化雙閉區間 [0, n-1]
|
||||
while (i <= j) {
|
||||
int m = i + (j - i) / 2; // 計算中點索引 m
|
||||
if (nums[m] < target) {
|
||||
i = m + 1; // target 在區間 [m+1, j] 中
|
||||
} else if (nums[m] > target) {
|
||||
j = m - 1; // target 在區間 [i, m-1] 中
|
||||
} else {
|
||||
j = m - 1; // 首個小於 target 的元素在區間 [i, m-1] 中
|
||||
}
|
||||
}
|
||||
// 返回插入點 i
|
||||
return i;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
// 無重複元素的陣列
|
||||
int[] nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35];
|
||||
Console.WriteLine("\n陣列 nums = " + nums.PrintList());
|
||||
// 二分搜尋插入點
|
||||
foreach (int target in new int[] { 6, 9 }) {
|
||||
int index = BinarySearchInsertionSimple(nums, target);
|
||||
Console.WriteLine("元素 " + target + " 的插入點的索引為 " + index);
|
||||
}
|
||||
|
||||
// 包含重複元素的陣列
|
||||
nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15];
|
||||
Console.WriteLine("\n陣列 nums = " + nums.PrintList());
|
||||
// 二分搜尋插入點
|
||||
foreach (int target in new int[] { 2, 6, 20 }) {
|
||||
int index = BinarySearchInsertion(nums, target);
|
||||
Console.WriteLine("元素 " + target + " 的插入點的索引為 " + index);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* File: hashing_search.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_searching;
|
||||
|
||||
public class hashing_search {
|
||||
/* 雜湊查詢(陣列) */
|
||||
int HashingSearchArray(Dictionary<int, int> map, int target) {
|
||||
// 雜湊表的 key: 目標元素,value: 索引
|
||||
// 若雜湊表中無此 key ,返回 -1
|
||||
return map.GetValueOrDefault(target, -1);
|
||||
}
|
||||
|
||||
/* 雜湊查詢(鏈結串列) */
|
||||
ListNode? HashingSearchLinkedList(Dictionary<int, ListNode> map, int target) {
|
||||
|
||||
// 雜湊表的 key: 目標節點值,value: 節點物件
|
||||
// 若雜湊表中無此 key ,返回 null
|
||||
return map.GetValueOrDefault(target);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int target = 3;
|
||||
|
||||
/* 雜湊查詢(陣列) */
|
||||
int[] nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8];
|
||||
// 初始化雜湊表
|
||||
Dictionary<int, int> map = [];
|
||||
for (int i = 0; i < nums.Length; i++) {
|
||||
map[nums[i]] = i; // key: 元素,value: 索引
|
||||
}
|
||||
int index = HashingSearchArray(map, target);
|
||||
Console.WriteLine("目標元素 3 的索引 = " + index);
|
||||
|
||||
/* 雜湊查詢(鏈結串列) */
|
||||
ListNode? head = ListNode.ArrToLinkedList(nums);
|
||||
// 初始化雜湊表
|
||||
Dictionary<int, ListNode> map1 = [];
|
||||
while (head != null) {
|
||||
map1[head.val] = head; // key: 節點值,value: 節點
|
||||
head = head.next;
|
||||
}
|
||||
ListNode? node = HashingSearchLinkedList(map1, target);
|
||||
Console.WriteLine("目標節點值 3 的對應節點物件為 " + node);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* File: linear_search.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_searching;
|
||||
|
||||
public class linear_search {
|
||||
/* 線性查詢(陣列) */
|
||||
int LinearSearchArray(int[] nums, int target) {
|
||||
// 走訪陣列
|
||||
for (int i = 0; i < nums.Length; i++) {
|
||||
// 找到目標元素,返回其索引
|
||||
if (nums[i] == target)
|
||||
return i;
|
||||
}
|
||||
// 未找到目標元素,返回 -1
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* 線性查詢(鏈結串列) */
|
||||
ListNode? LinearSearchLinkedList(ListNode? head, int target) {
|
||||
// 走訪鏈結串列
|
||||
while (head != null) {
|
||||
// 找到目標節點,返回之
|
||||
if (head.val == target)
|
||||
return head;
|
||||
head = head.next;
|
||||
}
|
||||
// 未找到目標節點,返回 null
|
||||
return null;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int target = 3;
|
||||
|
||||
/* 在陣列中執行線性查詢 */
|
||||
int[] nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8];
|
||||
int index = LinearSearchArray(nums, target);
|
||||
Console.WriteLine("目標元素 3 的索引 = " + index);
|
||||
|
||||
/* 在鏈結串列中執行線性查詢 */
|
||||
ListNode? head = ListNode.ArrToLinkedList(nums);
|
||||
ListNode? node = LinearSearchLinkedList(head, target);
|
||||
Console.WriteLine("目標節點值 3 的對應節點物件為 " + node);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* File: two_sum.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_searching;
|
||||
|
||||
public class two_sum {
|
||||
/* 方法一:暴力列舉 */
|
||||
int[] TwoSumBruteForce(int[] nums, int target) {
|
||||
int size = nums.Length;
|
||||
// 兩層迴圈,時間複雜度為 O(n^2)
|
||||
for (int i = 0; i < size - 1; i++) {
|
||||
for (int j = i + 1; j < size; j++) {
|
||||
if (nums[i] + nums[j] == target)
|
||||
return [i, j];
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/* 方法二:輔助雜湊表 */
|
||||
int[] TwoSumHashTable(int[] nums, int target) {
|
||||
int size = nums.Length;
|
||||
// 輔助雜湊表,空間複雜度為 O(n)
|
||||
Dictionary<int, int> dic = [];
|
||||
// 單層迴圈,時間複雜度為 O(n)
|
||||
for (int i = 0; i < size; i++) {
|
||||
if (dic.ContainsKey(target - nums[i])) {
|
||||
return [dic[target - nums[i]], i];
|
||||
}
|
||||
dic.Add(nums[i], i);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
// ======= Test Case =======
|
||||
int[] nums = [2, 7, 11, 15];
|
||||
int target = 13;
|
||||
|
||||
// ====== Driver Code ======
|
||||
// 方法一
|
||||
int[] res = TwoSumBruteForce(nums, target);
|
||||
Console.WriteLine("方法一 res = " + string.Join(",", res));
|
||||
// 方法二
|
||||
res = TwoSumHashTable(nums, target);
|
||||
Console.WriteLine("方法二 res = " + string.Join(",", res));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* File: bubble_sort.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_sorting;
|
||||
|
||||
public class bubble_sort {
|
||||
/* 泡沫排序 */
|
||||
void BubbleSort(int[] nums) {
|
||||
// 外迴圈:未排序區間為 [0, i]
|
||||
for (int i = nums.Length - 1; i > 0; i--) {
|
||||
// 內迴圈:將未排序區間 [0, i] 中的最大元素交換至該區間的最右端
|
||||
for (int j = 0; j < i; j++) {
|
||||
if (nums[j] > nums[j + 1]) {
|
||||
// 交換 nums[j] 與 nums[j + 1]
|
||||
(nums[j + 1], nums[j]) = (nums[j], nums[j + 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 泡沫排序(標誌最佳化)*/
|
||||
void BubbleSortWithFlag(int[] nums) {
|
||||
// 外迴圈:未排序區間為 [0, i]
|
||||
for (int i = nums.Length - 1; i > 0; i--) {
|
||||
bool flag = false; // 初始化標誌位
|
||||
// 內迴圈:將未排序區間 [0, i] 中的最大元素交換至該區間的最右端
|
||||
for (int j = 0; j < i; j++) {
|
||||
if (nums[j] > nums[j + 1]) {
|
||||
// 交換 nums[j] 與 nums[j + 1]
|
||||
(nums[j + 1], nums[j]) = (nums[j], nums[j + 1]);
|
||||
flag = true; // 記錄交換元素
|
||||
}
|
||||
}
|
||||
if (!flag) break; // 此輪“冒泡”未交換任何元素,直接跳出
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int[] nums = [4, 1, 3, 1, 5, 2];
|
||||
BubbleSort(nums);
|
||||
Console.WriteLine("泡沫排序完成後 nums = " + string.Join(",", nums));
|
||||
|
||||
int[] nums1 = [4, 1, 3, 1, 5, 2];
|
||||
BubbleSortWithFlag(nums1);
|
||||
Console.WriteLine("泡沫排序完成後 nums1 = " + string.Join(",", nums1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* File: bucket_sort.cs
|
||||
* Created Time: 2023-04-13
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_sorting;
|
||||
|
||||
public class bucket_sort {
|
||||
/* 桶排序 */
|
||||
void BucketSort(float[] nums) {
|
||||
// 初始化 k = n/2 個桶,預期向每個桶分配 2 個元素
|
||||
int k = nums.Length / 2;
|
||||
List<List<float>> buckets = [];
|
||||
for (int i = 0; i < k; i++) {
|
||||
buckets.Add([]);
|
||||
}
|
||||
// 1. 將陣列元素分配到各個桶中
|
||||
foreach (float num in nums) {
|
||||
// 輸入資料範圍為 [0, 1),使用 num * k 對映到索引範圍 [0, k-1]
|
||||
int i = (int)(num * k);
|
||||
// 將 num 新增進桶 i
|
||||
buckets[i].Add(num);
|
||||
}
|
||||
// 2. 對各個桶執行排序
|
||||
foreach (List<float> bucket in buckets) {
|
||||
// 使用內建排序函式,也可以替換成其他排序演算法
|
||||
bucket.Sort();
|
||||
}
|
||||
// 3. 走訪桶合併結果
|
||||
int j = 0;
|
||||
foreach (List<float> bucket in buckets) {
|
||||
foreach (float num in bucket) {
|
||||
nums[j++] = num;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
// 設輸入資料為浮點數,範圍為 [0, 1)
|
||||
float[] nums = [0.49f, 0.96f, 0.82f, 0.09f, 0.57f, 0.43f, 0.91f, 0.75f, 0.15f, 0.37f];
|
||||
BucketSort(nums);
|
||||
Console.WriteLine("桶排序完成後 nums = " + string.Join(" ", nums));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* File: counting_sort.cs
|
||||
* Created Time: 2023-04-13
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_sorting;
|
||||
|
||||
public class counting_sort {
|
||||
/* 計數排序 */
|
||||
// 簡單實現,無法用於排序物件
|
||||
void CountingSortNaive(int[] nums) {
|
||||
// 1. 統計陣列最大元素 m
|
||||
int m = 0;
|
||||
foreach (int num in nums) {
|
||||
m = Math.Max(m, num);
|
||||
}
|
||||
// 2. 統計各數字的出現次數
|
||||
// counter[num] 代表 num 的出現次數
|
||||
int[] counter = new int[m + 1];
|
||||
foreach (int num in nums) {
|
||||
counter[num]++;
|
||||
}
|
||||
// 3. 走訪 counter ,將各元素填入原陣列 nums
|
||||
int i = 0;
|
||||
for (int num = 0; num < m + 1; num++) {
|
||||
for (int j = 0; j < counter[num]; j++, i++) {
|
||||
nums[i] = num;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 計數排序 */
|
||||
// 完整實現,可排序物件,並且是穩定排序
|
||||
void CountingSort(int[] nums) {
|
||||
// 1. 統計陣列最大元素 m
|
||||
int m = 0;
|
||||
foreach (int num in nums) {
|
||||
m = Math.Max(m, num);
|
||||
}
|
||||
// 2. 統計各數字的出現次數
|
||||
// counter[num] 代表 num 的出現次數
|
||||
int[] counter = new int[m + 1];
|
||||
foreach (int num in nums) {
|
||||
counter[num]++;
|
||||
}
|
||||
// 3. 求 counter 的前綴和,將“出現次數”轉換為“尾索引”
|
||||
// 即 counter[num]-1 是 num 在 res 中最後一次出現的索引
|
||||
for (int i = 0; i < m; i++) {
|
||||
counter[i + 1] += counter[i];
|
||||
}
|
||||
// 4. 倒序走訪 nums ,將各元素填入結果陣列 res
|
||||
// 初始化陣列 res 用於記錄結果
|
||||
int n = nums.Length;
|
||||
int[] res = new int[n];
|
||||
for (int i = n - 1; i >= 0; i--) {
|
||||
int num = nums[i];
|
||||
res[counter[num] - 1] = num; // 將 num 放置到對應索引處
|
||||
counter[num]--; // 令前綴和自減 1 ,得到下次放置 num 的索引
|
||||
}
|
||||
// 使用結果陣列 res 覆蓋原陣列 nums
|
||||
for (int i = 0; i < n; i++) {
|
||||
nums[i] = res[i];
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int[] nums = [1, 0, 1, 2, 0, 4, 0, 2, 2, 4];
|
||||
CountingSortNaive(nums);
|
||||
Console.WriteLine("計數排序(無法排序物件)完成後 nums = " + string.Join(" ", nums));
|
||||
|
||||
int[] nums1 = [1, 0, 1, 2, 0, 4, 0, 2, 2, 4];
|
||||
CountingSort(nums1);
|
||||
Console.WriteLine("計數排序完成後 nums1 = " + string.Join(" ", nums));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* File: heap_sort.cs
|
||||
* Created Time: 2023-06-01
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_sorting;
|
||||
|
||||
public class heap_sort {
|
||||
/* 堆積的長度為 n ,從節點 i 開始,從頂至底堆積化 */
|
||||
void SiftDown(int[] nums, int n, int i) {
|
||||
while (true) {
|
||||
// 判斷節點 i, l, r 中值最大的節點,記為 ma
|
||||
int l = 2 * i + 1;
|
||||
int r = 2 * i + 2;
|
||||
int ma = i;
|
||||
if (l < n && nums[l] > nums[ma])
|
||||
ma = l;
|
||||
if (r < n && nums[r] > nums[ma])
|
||||
ma = r;
|
||||
// 若節點 i 最大或索引 l, r 越界,則無須繼續堆積化,跳出
|
||||
if (ma == i)
|
||||
break;
|
||||
// 交換兩節點
|
||||
(nums[ma], nums[i]) = (nums[i], nums[ma]);
|
||||
// 迴圈向下堆積化
|
||||
i = ma;
|
||||
}
|
||||
}
|
||||
|
||||
/* 堆積排序 */
|
||||
void HeapSort(int[] nums) {
|
||||
// 建堆積操作:堆積化除葉節點以外的其他所有節點
|
||||
for (int i = nums.Length / 2 - 1; i >= 0; i--) {
|
||||
SiftDown(nums, nums.Length, i);
|
||||
}
|
||||
// 從堆積中提取最大元素,迴圈 n-1 輪
|
||||
for (int i = nums.Length - 1; i > 0; i--) {
|
||||
// 交換根節點與最右葉節點(交換首元素與尾元素)
|
||||
(nums[i], nums[0]) = (nums[0], nums[i]);
|
||||
// 以根節點為起點,從頂至底進行堆積化
|
||||
SiftDown(nums, i, 0);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int[] nums = [4, 1, 3, 1, 5, 2];
|
||||
HeapSort(nums);
|
||||
Console.WriteLine("堆積排序完成後 nums = " + string.Join(" ", nums));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* File: insertion_sort.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_sorting;
|
||||
|
||||
public class insertion_sort {
|
||||
/* 插入排序 */
|
||||
void InsertionSort(int[] nums) {
|
||||
// 外迴圈:已排序區間為 [0, i-1]
|
||||
for (int i = 1; i < nums.Length; i++) {
|
||||
int bas = nums[i], j = i - 1;
|
||||
// 內迴圈:將 base 插入到已排序區間 [0, i-1] 中的正確位置
|
||||
while (j >= 0 && nums[j] > bas) {
|
||||
nums[j + 1] = nums[j]; // 將 nums[j] 向右移動一位
|
||||
j--;
|
||||
}
|
||||
nums[j + 1] = bas; // 將 base 賦值到正確位置
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int[] nums = [4, 1, 3, 1, 5, 2];
|
||||
InsertionSort(nums);
|
||||
Console.WriteLine("插入排序完成後 nums = " + string.Join(",", nums));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* File: merge_sort.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_sorting;
|
||||
|
||||
public class merge_sort {
|
||||
/* 合併左子陣列和右子陣列 */
|
||||
void Merge(int[] nums, int left, int mid, int right) {
|
||||
// 左子陣列區間為 [left, mid], 右子陣列區間為 [mid+1, right]
|
||||
// 建立一個臨時陣列 tmp ,用於存放合併後的結果
|
||||
int[] tmp = new int[right - left + 1];
|
||||
// 初始化左子陣列和右子陣列的起始索引
|
||||
int i = left, j = mid + 1, k = 0;
|
||||
// 當左右子陣列都還有元素時,進行比較並將較小的元素複製到臨時陣列中
|
||||
while (i <= mid && j <= right) {
|
||||
if (nums[i] <= nums[j])
|
||||
tmp[k++] = nums[i++];
|
||||
else
|
||||
tmp[k++] = nums[j++];
|
||||
}
|
||||
// 將左子陣列和右子陣列的剩餘元素複製到臨時陣列中
|
||||
while (i <= mid) {
|
||||
tmp[k++] = nums[i++];
|
||||
}
|
||||
while (j <= right) {
|
||||
tmp[k++] = nums[j++];
|
||||
}
|
||||
// 將臨時陣列 tmp 中的元素複製回原陣列 nums 的對應區間
|
||||
for (k = 0; k < tmp.Length; ++k) {
|
||||
nums[left + k] = tmp[k];
|
||||
}
|
||||
}
|
||||
|
||||
/* 合併排序 */
|
||||
void MergeSort(int[] nums, int left, int right) {
|
||||
// 終止條件
|
||||
if (left >= right) return; // 當子陣列長度為 1 時終止遞迴
|
||||
// 劃分階段
|
||||
int mid = (left + right) / 2; // 計算中點
|
||||
MergeSort(nums, left, mid); // 遞迴左子陣列
|
||||
MergeSort(nums, mid + 1, right); // 遞迴右子陣列
|
||||
// 合併階段
|
||||
Merge(nums, left, mid, right);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
/* 合併排序 */
|
||||
int[] nums = [7, 3, 2, 6, 0, 1, 5, 4];
|
||||
MergeSort(nums, 0, nums.Length - 1);
|
||||
Console.WriteLine("合併排序完成後 nums = " + string.Join(",", nums));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
/**
|
||||
* File: quick_sort.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_sorting;
|
||||
|
||||
class quickSort {
|
||||
/* 元素交換 */
|
||||
static void Swap(int[] nums, int i, int j) {
|
||||
(nums[j], nums[i]) = (nums[i], nums[j]);
|
||||
}
|
||||
|
||||
/* 哨兵劃分 */
|
||||
static int Partition(int[] nums, int left, int right) {
|
||||
// 以 nums[left] 為基準數
|
||||
int i = left, j = right;
|
||||
while (i < j) {
|
||||
while (i < j && nums[j] >= nums[left])
|
||||
j--; // 從右向左找首個小於基準數的元素
|
||||
while (i < j && nums[i] <= nums[left])
|
||||
i++; // 從左向右找首個大於基準數的元素
|
||||
Swap(nums, i, j); // 交換這兩個元素
|
||||
}
|
||||
Swap(nums, i, left); // 將基準數交換至兩子陣列的分界線
|
||||
return i; // 返回基準數的索引
|
||||
}
|
||||
|
||||
/* 快速排序 */
|
||||
public static void QuickSort(int[] nums, int left, int right) {
|
||||
// 子陣列長度為 1 時終止遞迴
|
||||
if (left >= right)
|
||||
return;
|
||||
// 哨兵劃分
|
||||
int pivot = Partition(nums, left, right);
|
||||
// 遞迴左子陣列、右子陣列
|
||||
QuickSort(nums, left, pivot - 1);
|
||||
QuickSort(nums, pivot + 1, right);
|
||||
}
|
||||
}
|
||||
|
||||
/* 快速排序類別(中位基準數最佳化) */
|
||||
class QuickSortMedian {
|
||||
/* 元素交換 */
|
||||
static void Swap(int[] nums, int i, int j) {
|
||||
(nums[j], nums[i]) = (nums[i], nums[j]);
|
||||
}
|
||||
|
||||
/* 選取三個候選元素的中位數 */
|
||||
static int MedianThree(int[] nums, int left, int mid, int right) {
|
||||
int l = nums[left], m = nums[mid], r = nums[right];
|
||||
if ((l <= m && m <= r) || (r <= m && m <= l))
|
||||
return mid; // m 在 l 和 r 之間
|
||||
if ((m <= l && l <= r) || (r <= l && l <= m))
|
||||
return left; // l 在 m 和 r 之間
|
||||
return right;
|
||||
}
|
||||
|
||||
/* 哨兵劃分(三數取中值) */
|
||||
static int Partition(int[] nums, int left, int right) {
|
||||
// 選取三個候選元素的中位數
|
||||
int med = MedianThree(nums, left, (left + right) / 2, right);
|
||||
// 將中位數交換至陣列最左端
|
||||
Swap(nums, left, med);
|
||||
// 以 nums[left] 為基準數
|
||||
int i = left, j = right;
|
||||
while (i < j) {
|
||||
while (i < j && nums[j] >= nums[left])
|
||||
j--; // 從右向左找首個小於基準數的元素
|
||||
while (i < j && nums[i] <= nums[left])
|
||||
i++; // 從左向右找首個大於基準數的元素
|
||||
Swap(nums, i, j); // 交換這兩個元素
|
||||
}
|
||||
Swap(nums, i, left); // 將基準數交換至兩子陣列的分界線
|
||||
return i; // 返回基準數的索引
|
||||
}
|
||||
|
||||
/* 快速排序 */
|
||||
public static void QuickSort(int[] nums, int left, int right) {
|
||||
// 子陣列長度為 1 時終止遞迴
|
||||
if (left >= right)
|
||||
return;
|
||||
// 哨兵劃分
|
||||
int pivot = Partition(nums, left, right);
|
||||
// 遞迴左子陣列、右子陣列
|
||||
QuickSort(nums, left, pivot - 1);
|
||||
QuickSort(nums, pivot + 1, right);
|
||||
}
|
||||
}
|
||||
|
||||
/* 快速排序類別(尾遞迴最佳化) */
|
||||
class QuickSortTailCall {
|
||||
/* 元素交換 */
|
||||
static void Swap(int[] nums, int i, int j) {
|
||||
(nums[j], nums[i]) = (nums[i], nums[j]);
|
||||
}
|
||||
|
||||
/* 哨兵劃分 */
|
||||
static int Partition(int[] nums, int left, int right) {
|
||||
// 以 nums[left] 為基準數
|
||||
int i = left, j = right;
|
||||
while (i < j) {
|
||||
while (i < j && nums[j] >= nums[left])
|
||||
j--; // 從右向左找首個小於基準數的元素
|
||||
while (i < j && nums[i] <= nums[left])
|
||||
i++; // 從左向右找首個大於基準數的元素
|
||||
Swap(nums, i, j); // 交換這兩個元素
|
||||
}
|
||||
Swap(nums, i, left); // 將基準數交換至兩子陣列的分界線
|
||||
return i; // 返回基準數的索引
|
||||
}
|
||||
|
||||
/* 快速排序(尾遞迴最佳化) */
|
||||
public static void QuickSort(int[] nums, int left, int right) {
|
||||
// 子陣列長度為 1 時終止
|
||||
while (left < right) {
|
||||
// 哨兵劃分操作
|
||||
int pivot = Partition(nums, left, right);
|
||||
// 對兩個子陣列中較短的那個執行快速排序
|
||||
if (pivot - left < right - pivot) {
|
||||
QuickSort(nums, left, pivot - 1); // 遞迴排序左子陣列
|
||||
left = pivot + 1; // 剩餘未排序區間為 [pivot + 1, right]
|
||||
} else {
|
||||
QuickSort(nums, pivot + 1, right); // 遞迴排序右子陣列
|
||||
right = pivot - 1; // 剩餘未排序區間為 [left, pivot - 1]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class quick_sort {
|
||||
[Test]
|
||||
public void Test() {
|
||||
/* 快速排序 */
|
||||
int[] nums = [2, 4, 1, 0, 3, 5];
|
||||
quickSort.QuickSort(nums, 0, nums.Length - 1);
|
||||
Console.WriteLine("快速排序完成後 nums = " + string.Join(",", nums));
|
||||
|
||||
/* 快速排序(中位基準數最佳化) */
|
||||
int[] nums1 = [2, 4, 1, 0, 3, 5];
|
||||
QuickSortMedian.QuickSort(nums1, 0, nums1.Length - 1);
|
||||
Console.WriteLine("快速排序(中位基準數最佳化)完成後 nums1 = " + string.Join(",", nums1));
|
||||
|
||||
/* 快速排序(尾遞迴最佳化) */
|
||||
int[] nums2 = [2, 4, 1, 0, 3, 5];
|
||||
QuickSortTailCall.QuickSort(nums2, 0, nums2.Length - 1);
|
||||
Console.WriteLine("快速排序(尾遞迴最佳化)完成後 nums2 = " + string.Join(",", nums2));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* File: radix_sort.cs
|
||||
* Created Time: 2023-04-13
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_sorting;
|
||||
|
||||
public class radix_sort {
|
||||
/* 獲取元素 num 的第 k 位,其中 exp = 10^(k-1) */
|
||||
int Digit(int num, int exp) {
|
||||
// 傳入 exp 而非 k 可以避免在此重複執行昂貴的次方計算
|
||||
return (num / exp) % 10;
|
||||
}
|
||||
|
||||
/* 計數排序(根據 nums 第 k 位排序) */
|
||||
void CountingSortDigit(int[] nums, int exp) {
|
||||
// 十進位制的位範圍為 0~9 ,因此需要長度為 10 的桶陣列
|
||||
int[] counter = new int[10];
|
||||
int n = nums.Length;
|
||||
// 統計 0~9 各數字的出現次數
|
||||
for (int i = 0; i < n; i++) {
|
||||
int d = Digit(nums[i], exp); // 獲取 nums[i] 第 k 位,記為 d
|
||||
counter[d]++; // 統計數字 d 的出現次數
|
||||
}
|
||||
// 求前綴和,將“出現個數”轉換為“陣列索引”
|
||||
for (int i = 1; i < 10; i++) {
|
||||
counter[i] += counter[i - 1];
|
||||
}
|
||||
// 倒序走訪,根據桶內統計結果,將各元素填入 res
|
||||
int[] res = new int[n];
|
||||
for (int i = n - 1; i >= 0; i--) {
|
||||
int d = Digit(nums[i], exp);
|
||||
int j = counter[d] - 1; // 獲取 d 在陣列中的索引 j
|
||||
res[j] = nums[i]; // 將當前元素填入索引 j
|
||||
counter[d]--; // 將 d 的數量減 1
|
||||
}
|
||||
// 使用結果覆蓋原陣列 nums
|
||||
for (int i = 0; i < n; i++) {
|
||||
nums[i] = res[i];
|
||||
}
|
||||
}
|
||||
|
||||
/* 基數排序 */
|
||||
void RadixSort(int[] nums) {
|
||||
// 獲取陣列的最大元素,用於判斷最大位數
|
||||
int m = int.MinValue;
|
||||
foreach (int num in nums) {
|
||||
if (num > m) m = num;
|
||||
}
|
||||
// 按照從低位到高位的順序走訪
|
||||
for (int exp = 1; exp <= m; exp *= 10) {
|
||||
// 對陣列元素的第 k 位執行計數排序
|
||||
// k = 1 -> exp = 1
|
||||
// k = 2 -> exp = 10
|
||||
// 即 exp = 10^(k-1)
|
||||
CountingSortDigit(nums, exp);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
// 基數排序
|
||||
int[] nums = [ 10546151, 35663510, 42865989, 34862445, 81883077,
|
||||
88906420, 72429244, 30524779, 82060337, 63832996 ];
|
||||
RadixSort(nums);
|
||||
Console.WriteLine("基數排序完成後 nums = " + string.Join(" ", nums));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* File: selection_sort.cs
|
||||
* Created Time: 2023-06-01
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_sorting;
|
||||
|
||||
public class selection_sort {
|
||||
/* 選擇排序 */
|
||||
void SelectionSort(int[] nums) {
|
||||
int n = nums.Length;
|
||||
// 外迴圈:未排序區間為 [i, n-1]
|
||||
for (int i = 0; i < n - 1; i++) {
|
||||
// 內迴圈:找到未排序區間內的最小元素
|
||||
int k = i;
|
||||
for (int j = i + 1; j < n; j++) {
|
||||
if (nums[j] < nums[k])
|
||||
k = j; // 記錄最小元素的索引
|
||||
}
|
||||
// 將該最小元素與未排序區間的首個元素交換
|
||||
(nums[k], nums[i]) = (nums[i], nums[k]);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int[] nums = [4, 1, 3, 1, 5, 2];
|
||||
SelectionSort(nums);
|
||||
Console.WriteLine("選擇排序完成後 nums = " + string.Join(" ", nums));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
* File: array_deque.cs
|
||||
* Created Time: 2023-03-08
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_stack_and_queue;
|
||||
|
||||
/* 基於環形陣列實現的雙向佇列 */
|
||||
public class ArrayDeque {
|
||||
int[] nums; // 用於儲存雙向佇列元素的陣列
|
||||
int front; // 佇列首指標,指向佇列首元素
|
||||
int queSize; // 雙向佇列長度
|
||||
|
||||
/* 建構子 */
|
||||
public ArrayDeque(int capacity) {
|
||||
nums = new int[capacity];
|
||||
front = queSize = 0;
|
||||
}
|
||||
|
||||
/* 獲取雙向佇列的容量 */
|
||||
int Capacity() {
|
||||
return nums.Length;
|
||||
}
|
||||
|
||||
/* 獲取雙向佇列的長度 */
|
||||
public int Size() {
|
||||
return queSize;
|
||||
}
|
||||
|
||||
/* 判斷雙向佇列是否為空 */
|
||||
public bool IsEmpty() {
|
||||
return queSize == 0;
|
||||
}
|
||||
|
||||
/* 計算環形陣列索引 */
|
||||
int Index(int i) {
|
||||
// 透過取餘操作實現陣列首尾相連
|
||||
// 當 i 越過陣列尾部後,回到頭部
|
||||
// 當 i 越過陣列頭部後,回到尾部
|
||||
return (i + Capacity()) % Capacity();
|
||||
}
|
||||
|
||||
/* 佇列首入列 */
|
||||
public void PushFirst(int num) {
|
||||
if (queSize == Capacity()) {
|
||||
Console.WriteLine("雙向佇列已滿");
|
||||
return;
|
||||
}
|
||||
// 佇列首指標向左移動一位
|
||||
// 透過取餘操作實現 front 越過陣列頭部後回到尾部
|
||||
front = Index(front - 1);
|
||||
// 將 num 新增至佇列首
|
||||
nums[front] = num;
|
||||
queSize++;
|
||||
}
|
||||
|
||||
/* 佇列尾入列 */
|
||||
public void PushLast(int num) {
|
||||
if (queSize == Capacity()) {
|
||||
Console.WriteLine("雙向佇列已滿");
|
||||
return;
|
||||
}
|
||||
// 計算佇列尾指標,指向佇列尾索引 + 1
|
||||
int rear = Index(front + queSize);
|
||||
// 將 num 新增至佇列尾
|
||||
nums[rear] = num;
|
||||
queSize++;
|
||||
}
|
||||
|
||||
/* 佇列首出列 */
|
||||
public int PopFirst() {
|
||||
int num = PeekFirst();
|
||||
// 佇列首指標向後移動一位
|
||||
front = Index(front + 1);
|
||||
queSize--;
|
||||
return num;
|
||||
}
|
||||
|
||||
/* 佇列尾出列 */
|
||||
public int PopLast() {
|
||||
int num = PeekLast();
|
||||
queSize--;
|
||||
return num;
|
||||
}
|
||||
|
||||
/* 訪問佇列首元素 */
|
||||
public int PeekFirst() {
|
||||
if (IsEmpty()) {
|
||||
throw new InvalidOperationException();
|
||||
}
|
||||
return nums[front];
|
||||
}
|
||||
|
||||
/* 訪問佇列尾元素 */
|
||||
public int PeekLast() {
|
||||
if (IsEmpty()) {
|
||||
throw new InvalidOperationException();
|
||||
}
|
||||
// 計算尾元素索引
|
||||
int last = Index(front + queSize - 1);
|
||||
return nums[last];
|
||||
}
|
||||
|
||||
/* 返回陣列用於列印 */
|
||||
public int[] ToArray() {
|
||||
// 僅轉換有效長度範圍內的串列元素
|
||||
int[] res = new int[queSize];
|
||||
for (int i = 0, j = front; i < queSize; i++, j++) {
|
||||
res[i] = nums[Index(j)];
|
||||
}
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
public class array_deque {
|
||||
[Test]
|
||||
public void Test() {
|
||||
/* 初始化雙向佇列 */
|
||||
ArrayDeque deque = new(10);
|
||||
deque.PushLast(3);
|
||||
deque.PushLast(2);
|
||||
deque.PushLast(5);
|
||||
Console.WriteLine("雙向佇列 deque = " + string.Join(" ", deque.ToArray()));
|
||||
|
||||
/* 訪問元素 */
|
||||
int peekFirst = deque.PeekFirst();
|
||||
Console.WriteLine("佇列首元素 peekFirst = " + peekFirst);
|
||||
int peekLast = deque.PeekLast();
|
||||
Console.WriteLine("佇列尾元素 peekLast = " + peekLast);
|
||||
|
||||
/* 元素入列 */
|
||||
deque.PushLast(4);
|
||||
Console.WriteLine("元素 4 佇列尾入列後 deque = " + string.Join(" ", deque.ToArray()));
|
||||
deque.PushFirst(1);
|
||||
Console.WriteLine("元素 1 佇列首入列後 deque = " + string.Join(" ", deque.ToArray()));
|
||||
|
||||
/* 元素出列 */
|
||||
int popLast = deque.PopLast();
|
||||
Console.WriteLine("佇列尾出列元素 = " + popLast + ",佇列尾出列後 deque = " + string.Join(" ", deque.ToArray()));
|
||||
int popFirst = deque.PopFirst();
|
||||
Console.WriteLine("佇列首出列元素 = " + popFirst + ",佇列首出列後 deque = " + string.Join(" ", deque.ToArray()));
|
||||
|
||||
/* 獲取雙向佇列的長度 */
|
||||
int size = deque.Size();
|
||||
Console.WriteLine("雙向佇列長度 size = " + size);
|
||||
|
||||
/* 判斷雙向佇列是否為空 */
|
||||
bool isEmpty = deque.IsEmpty();
|
||||
Console.WriteLine("雙向佇列是否為空 = " + isEmpty);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* File: array_queue.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_stack_and_queue;
|
||||
|
||||
/* 基於環形陣列實現的佇列 */
|
||||
class ArrayQueue {
|
||||
int[] nums; // 用於儲存佇列元素的陣列
|
||||
int front; // 佇列首指標,指向佇列首元素
|
||||
int queSize; // 佇列長度
|
||||
|
||||
public ArrayQueue(int capacity) {
|
||||
nums = new int[capacity];
|
||||
front = queSize = 0;
|
||||
}
|
||||
|
||||
/* 獲取佇列的容量 */
|
||||
int Capacity() {
|
||||
return nums.Length;
|
||||
}
|
||||
|
||||
/* 獲取佇列的長度 */
|
||||
public int Size() {
|
||||
return queSize;
|
||||
}
|
||||
|
||||
/* 判斷佇列是否為空 */
|
||||
public bool IsEmpty() {
|
||||
return queSize == 0;
|
||||
}
|
||||
|
||||
/* 入列 */
|
||||
public void Push(int num) {
|
||||
if (queSize == Capacity()) {
|
||||
Console.WriteLine("佇列已滿");
|
||||
return;
|
||||
}
|
||||
// 計算佇列尾指標,指向佇列尾索引 + 1
|
||||
// 透過取餘操作實現 rear 越過陣列尾部後回到頭部
|
||||
int rear = (front + queSize) % Capacity();
|
||||
// 將 num 新增至佇列尾
|
||||
nums[rear] = num;
|
||||
queSize++;
|
||||
}
|
||||
|
||||
/* 出列 */
|
||||
public int Pop() {
|
||||
int num = Peek();
|
||||
// 佇列首指標向後移動一位,若越過尾部,則返回到陣列頭部
|
||||
front = (front + 1) % Capacity();
|
||||
queSize--;
|
||||
return num;
|
||||
}
|
||||
|
||||
/* 訪問佇列首元素 */
|
||||
public int Peek() {
|
||||
if (IsEmpty())
|
||||
throw new Exception();
|
||||
return nums[front];
|
||||
}
|
||||
|
||||
/* 返回陣列 */
|
||||
public int[] ToArray() {
|
||||
// 僅轉換有效長度範圍內的串列元素
|
||||
int[] res = new int[queSize];
|
||||
for (int i = 0, j = front; i < queSize; i++, j++) {
|
||||
res[i] = nums[j % this.Capacity()];
|
||||
}
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
public class array_queue {
|
||||
[Test]
|
||||
public void Test() {
|
||||
/* 初始化佇列 */
|
||||
int capacity = 10;
|
||||
ArrayQueue queue = new(capacity);
|
||||
|
||||
/* 元素入列 */
|
||||
queue.Push(1);
|
||||
queue.Push(3);
|
||||
queue.Push(2);
|
||||
queue.Push(5);
|
||||
queue.Push(4);
|
||||
Console.WriteLine("佇列 queue = " + string.Join(",", queue.ToArray()));
|
||||
|
||||
/* 訪問佇列首元素 */
|
||||
int peek = queue.Peek();
|
||||
Console.WriteLine("佇列首元素 peek = " + peek);
|
||||
|
||||
/* 元素出列 */
|
||||
int pop = queue.Pop();
|
||||
Console.WriteLine("出列元素 pop = " + pop + ",出列後 queue = " + string.Join(",", queue.ToArray()));
|
||||
|
||||
/* 獲取佇列的長度 */
|
||||
int size = queue.Size();
|
||||
Console.WriteLine("佇列長度 size = " + size);
|
||||
|
||||
/* 判斷佇列是否為空 */
|
||||
bool isEmpty = queue.IsEmpty();
|
||||
Console.WriteLine("佇列是否為空 = " + isEmpty);
|
||||
|
||||
/* 測試環形陣列 */
|
||||
for (int i = 0; i < 10; i++) {
|
||||
queue.Push(i);
|
||||
queue.Pop();
|
||||
Console.WriteLine("第 " + i + " 輪入列 + 出列後 queue = " + string.Join(",", queue.ToArray()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* File: array_stack.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_stack_and_queue;
|
||||
|
||||
/* 基於陣列實現的堆疊 */
|
||||
class ArrayStack {
|
||||
List<int> stack;
|
||||
public ArrayStack() {
|
||||
// 初始化串列(動態陣列)
|
||||
stack = [];
|
||||
}
|
||||
|
||||
/* 獲取堆疊的長度 */
|
||||
public int Size() {
|
||||
return stack.Count;
|
||||
}
|
||||
|
||||
/* 判斷堆疊是否為空 */
|
||||
public bool IsEmpty() {
|
||||
return Size() == 0;
|
||||
}
|
||||
|
||||
/* 入堆疊 */
|
||||
public void Push(int num) {
|
||||
stack.Add(num);
|
||||
}
|
||||
|
||||
/* 出堆疊 */
|
||||
public int Pop() {
|
||||
if (IsEmpty())
|
||||
throw new Exception();
|
||||
var val = Peek();
|
||||
stack.RemoveAt(Size() - 1);
|
||||
return val;
|
||||
}
|
||||
|
||||
/* 訪問堆疊頂元素 */
|
||||
public int Peek() {
|
||||
if (IsEmpty())
|
||||
throw new Exception();
|
||||
return stack[Size() - 1];
|
||||
}
|
||||
|
||||
/* 將 List 轉化為 Array 並返回 */
|
||||
public int[] ToArray() {
|
||||
return [.. stack];
|
||||
}
|
||||
}
|
||||
|
||||
public class array_stack {
|
||||
[Test]
|
||||
public void Test() {
|
||||
/* 初始化堆疊 */
|
||||
ArrayStack stack = new();
|
||||
|
||||
/* 元素入堆疊 */
|
||||
stack.Push(1);
|
||||
stack.Push(3);
|
||||
stack.Push(2);
|
||||
stack.Push(5);
|
||||
stack.Push(4);
|
||||
Console.WriteLine("堆疊 stack = " + string.Join(",", stack.ToArray()));
|
||||
|
||||
/* 訪問堆疊頂元素 */
|
||||
int peek = stack.Peek();
|
||||
Console.WriteLine("堆疊頂元素 peek = " + peek);
|
||||
|
||||
/* 元素出堆疊 */
|
||||
int pop = stack.Pop();
|
||||
Console.WriteLine("出堆疊元素 pop = " + pop + ",出堆疊後 stack = " + string.Join(",", stack.ToArray()));
|
||||
|
||||
/* 獲取堆疊的長度 */
|
||||
int size = stack.Size();
|
||||
Console.WriteLine("堆疊的長度 size = " + size);
|
||||
|
||||
/* 判斷是否為空 */
|
||||
bool isEmpty = stack.IsEmpty();
|
||||
Console.WriteLine("堆疊是否為空 = " + isEmpty);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* File: deque.cs
|
||||
* Created Time: 2022-12-30
|
||||
* Author: moonache (microin1301@outlook.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_stack_and_queue;
|
||||
|
||||
public class deque {
|
||||
[Test]
|
||||
public void Test() {
|
||||
/* 初始化雙向佇列 */
|
||||
// 在 C# 中,將鏈結串列 LinkedList 看作雙向佇列來使用
|
||||
LinkedList<int> deque = new();
|
||||
|
||||
/* 元素入列 */
|
||||
deque.AddLast(2); // 新增至佇列尾
|
||||
deque.AddLast(5);
|
||||
deque.AddLast(4);
|
||||
deque.AddFirst(3); // 新增至佇列首
|
||||
deque.AddFirst(1);
|
||||
Console.WriteLine("雙向佇列 deque = " + string.Join(",", deque));
|
||||
|
||||
/* 訪問元素 */
|
||||
int? peekFirst = deque.First?.Value; // 佇列首元素
|
||||
Console.WriteLine("佇列首元素 peekFirst = " + peekFirst);
|
||||
int? peekLast = deque.Last?.Value; // 佇列尾元素
|
||||
Console.WriteLine("佇列尾元素 peekLast = " + peekLast);
|
||||
|
||||
/* 元素出列 */
|
||||
deque.RemoveFirst(); // 佇列首元素出列
|
||||
Console.WriteLine("佇列首元素出列後 deque = " + string.Join(",", deque));
|
||||
deque.RemoveLast(); // 佇列尾元素出列
|
||||
Console.WriteLine("佇列尾元素出列後 deque = " + string.Join(",", deque));
|
||||
|
||||
/* 獲取雙向佇列的長度 */
|
||||
int size = deque.Count;
|
||||
Console.WriteLine("雙向佇列長度 size = " + size);
|
||||
|
||||
/* 判斷雙向佇列是否為空 */
|
||||
bool isEmpty = deque.Count == 0;
|
||||
Console.WriteLine("雙向佇列是否為空 = " + isEmpty);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
/**
|
||||
* File: linkedlist_deque.cs
|
||||
* Created Time: 2023-03-08
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_stack_and_queue;
|
||||
|
||||
/* 雙向鏈結串列節點 */
|
||||
public class ListNode(int val) {
|
||||
public int val = val; // 節點值
|
||||
public ListNode? next = null; // 後繼節點引用
|
||||
public ListNode? prev = null; // 前驅節點引用
|
||||
}
|
||||
|
||||
/* 基於雙向鏈結串列實現的雙向佇列 */
|
||||
public class LinkedListDeque {
|
||||
ListNode? front, rear; // 頭節點 front, 尾節點 rear
|
||||
int queSize = 0; // 雙向佇列的長度
|
||||
|
||||
public LinkedListDeque() {
|
||||
front = null;
|
||||
rear = null;
|
||||
}
|
||||
|
||||
/* 獲取雙向佇列的長度 */
|
||||
public int Size() {
|
||||
return queSize;
|
||||
}
|
||||
|
||||
/* 判斷雙向佇列是否為空 */
|
||||
public bool IsEmpty() {
|
||||
return Size() == 0;
|
||||
}
|
||||
|
||||
/* 入列操作 */
|
||||
void Push(int num, bool isFront) {
|
||||
ListNode node = new(num);
|
||||
// 若鏈結串列為空,則令 front 和 rear 都指向 node
|
||||
if (IsEmpty()) {
|
||||
front = node;
|
||||
rear = node;
|
||||
}
|
||||
// 佇列首入列操作
|
||||
else if (isFront) {
|
||||
// 將 node 新增至鏈結串列頭部
|
||||
front!.prev = node;
|
||||
node.next = front;
|
||||
front = node; // 更新頭節點
|
||||
}
|
||||
// 佇列尾入列操作
|
||||
else {
|
||||
// 將 node 新增至鏈結串列尾部
|
||||
rear!.next = node;
|
||||
node.prev = rear;
|
||||
rear = node; // 更新尾節點
|
||||
}
|
||||
|
||||
queSize++; // 更新佇列長度
|
||||
}
|
||||
|
||||
/* 佇列首入列 */
|
||||
public void PushFirst(int num) {
|
||||
Push(num, true);
|
||||
}
|
||||
|
||||
/* 佇列尾入列 */
|
||||
public void PushLast(int num) {
|
||||
Push(num, false);
|
||||
}
|
||||
|
||||
/* 出列操作 */
|
||||
int? Pop(bool isFront) {
|
||||
if (IsEmpty())
|
||||
throw new Exception();
|
||||
int? val;
|
||||
// 佇列首出列操作
|
||||
if (isFront) {
|
||||
val = front?.val; // 暫存頭節點值
|
||||
// 刪除頭節點
|
||||
ListNode? fNext = front?.next;
|
||||
if (fNext != null) {
|
||||
fNext.prev = null;
|
||||
front!.next = null;
|
||||
}
|
||||
front = fNext; // 更新頭節點
|
||||
}
|
||||
// 佇列尾出列操作
|
||||
else {
|
||||
val = rear?.val; // 暫存尾節點值
|
||||
// 刪除尾節點
|
||||
ListNode? rPrev = rear?.prev;
|
||||
if (rPrev != null) {
|
||||
rPrev.next = null;
|
||||
rear!.prev = null;
|
||||
}
|
||||
rear = rPrev; // 更新尾節點
|
||||
}
|
||||
|
||||
queSize--; // 更新佇列長度
|
||||
return val;
|
||||
}
|
||||
|
||||
/* 佇列首出列 */
|
||||
public int? PopFirst() {
|
||||
return Pop(true);
|
||||
}
|
||||
|
||||
/* 佇列尾出列 */
|
||||
public int? PopLast() {
|
||||
return Pop(false);
|
||||
}
|
||||
|
||||
/* 訪問佇列首元素 */
|
||||
public int? PeekFirst() {
|
||||
if (IsEmpty())
|
||||
throw new Exception();
|
||||
return front?.val;
|
||||
}
|
||||
|
||||
/* 訪問佇列尾元素 */
|
||||
public int? PeekLast() {
|
||||
if (IsEmpty())
|
||||
throw new Exception();
|
||||
return rear?.val;
|
||||
}
|
||||
|
||||
/* 返回陣列用於列印 */
|
||||
public int?[] ToArray() {
|
||||
ListNode? node = front;
|
||||
int?[] res = new int?[Size()];
|
||||
for (int i = 0; i < res.Length; i++) {
|
||||
res[i] = node?.val;
|
||||
node = node?.next;
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
public class linkedlist_deque {
|
||||
[Test]
|
||||
public void Test() {
|
||||
/* 初始化雙向佇列 */
|
||||
LinkedListDeque deque = new();
|
||||
deque.PushLast(3);
|
||||
deque.PushLast(2);
|
||||
deque.PushLast(5);
|
||||
Console.WriteLine("雙向佇列 deque = " + string.Join(" ", deque.ToArray()));
|
||||
|
||||
/* 訪問元素 */
|
||||
int? peekFirst = deque.PeekFirst();
|
||||
Console.WriteLine("佇列首元素 peekFirst = " + peekFirst);
|
||||
int? peekLast = deque.PeekLast();
|
||||
Console.WriteLine("佇列尾元素 peekLast = " + peekLast);
|
||||
|
||||
/* 元素入列 */
|
||||
deque.PushLast(4);
|
||||
Console.WriteLine("元素 4 佇列尾入列後 deque = " + string.Join(" ", deque.ToArray()));
|
||||
deque.PushFirst(1);
|
||||
Console.WriteLine("元素 1 佇列首入列後 deque = " + string.Join(" ", deque.ToArray()));
|
||||
|
||||
/* 元素出列 */
|
||||
int? popLast = deque.PopLast();
|
||||
Console.WriteLine("佇列尾出列元素 = " + popLast + ",佇列尾出列後 deque = " + string.Join(" ", deque.ToArray()));
|
||||
int? popFirst = deque.PopFirst();
|
||||
Console.WriteLine("佇列首出列元素 = " + popFirst + ",佇列首出列後 deque = " + string.Join(" ", deque.ToArray()));
|
||||
|
||||
/* 獲取雙向佇列的長度 */
|
||||
int size = deque.Size();
|
||||
Console.WriteLine("雙向佇列長度 size = " + size);
|
||||
|
||||
/* 判斷雙向佇列是否為空 */
|
||||
bool isEmpty = deque.IsEmpty();
|
||||
Console.WriteLine("雙向佇列是否為空 = " + isEmpty);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* File: linkedlist_queue.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_stack_and_queue;
|
||||
|
||||
/* 基於鏈結串列實現的佇列 */
|
||||
class LinkedListQueue {
|
||||
ListNode? front, rear; // 頭節點 front ,尾節點 rear
|
||||
int queSize = 0;
|
||||
|
||||
public LinkedListQueue() {
|
||||
front = null;
|
||||
rear = null;
|
||||
}
|
||||
|
||||
/* 獲取佇列的長度 */
|
||||
public int Size() {
|
||||
return queSize;
|
||||
}
|
||||
|
||||
/* 判斷佇列是否為空 */
|
||||
public bool IsEmpty() {
|
||||
return Size() == 0;
|
||||
}
|
||||
|
||||
/* 入列 */
|
||||
public void Push(int num) {
|
||||
// 在尾節點後新增 num
|
||||
ListNode node = new(num);
|
||||
// 如果佇列為空,則令頭、尾節點都指向該節點
|
||||
if (front == null) {
|
||||
front = node;
|
||||
rear = node;
|
||||
// 如果佇列不為空,則將該節點新增到尾節點後
|
||||
} else if (rear != null) {
|
||||
rear.next = node;
|
||||
rear = node;
|
||||
}
|
||||
queSize++;
|
||||
}
|
||||
|
||||
/* 出列 */
|
||||
public int Pop() {
|
||||
int num = Peek();
|
||||
// 刪除頭節點
|
||||
front = front?.next;
|
||||
queSize--;
|
||||
return num;
|
||||
}
|
||||
|
||||
/* 訪問佇列首元素 */
|
||||
public int Peek() {
|
||||
if (IsEmpty())
|
||||
throw new Exception();
|
||||
return front!.val;
|
||||
}
|
||||
|
||||
/* 將鏈結串列轉化為 Array 並返回 */
|
||||
public int[] ToArray() {
|
||||
if (front == null)
|
||||
return [];
|
||||
|
||||
ListNode? node = front;
|
||||
int[] res = new int[Size()];
|
||||
for (int i = 0; i < res.Length; i++) {
|
||||
res[i] = node!.val;
|
||||
node = node.next;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
public class linkedlist_queue {
|
||||
[Test]
|
||||
public void Test() {
|
||||
/* 初始化佇列 */
|
||||
LinkedListQueue queue = new();
|
||||
|
||||
/* 元素入列 */
|
||||
queue.Push(1);
|
||||
queue.Push(3);
|
||||
queue.Push(2);
|
||||
queue.Push(5);
|
||||
queue.Push(4);
|
||||
Console.WriteLine("佇列 queue = " + string.Join(",", queue.ToArray()));
|
||||
|
||||
/* 訪問佇列首元素 */
|
||||
int peek = queue.Peek();
|
||||
Console.WriteLine("佇列首元素 peek = " + peek);
|
||||
|
||||
/* 元素出列 */
|
||||
int pop = queue.Pop();
|
||||
Console.WriteLine("出列元素 pop = " + pop + ",出列後 queue = " + string.Join(",", queue.ToArray()));
|
||||
|
||||
/* 獲取佇列的長度 */
|
||||
int size = queue.Size();
|
||||
Console.WriteLine("佇列長度 size = " + size);
|
||||
|
||||
/* 判斷佇列是否為空 */
|
||||
bool isEmpty = queue.IsEmpty();
|
||||
Console.WriteLine("佇列是否為空 = " + isEmpty);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
/**
|
||||
* File: linkedlist_stack.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_stack_and_queue;
|
||||
|
||||
/* 基於鏈結串列實現的堆疊 */
|
||||
class LinkedListStack {
|
||||
ListNode? stackPeek; // 將頭節點作為堆疊頂
|
||||
int stkSize = 0; // 堆疊的長度
|
||||
|
||||
public LinkedListStack() {
|
||||
stackPeek = null;
|
||||
}
|
||||
|
||||
/* 獲取堆疊的長度 */
|
||||
public int Size() {
|
||||
return stkSize;
|
||||
}
|
||||
|
||||
/* 判斷堆疊是否為空 */
|
||||
public bool IsEmpty() {
|
||||
return Size() == 0;
|
||||
}
|
||||
|
||||
/* 入堆疊 */
|
||||
public void Push(int num) {
|
||||
ListNode node = new(num) {
|
||||
next = stackPeek
|
||||
};
|
||||
stackPeek = node;
|
||||
stkSize++;
|
||||
}
|
||||
|
||||
/* 出堆疊 */
|
||||
public int Pop() {
|
||||
int num = Peek();
|
||||
stackPeek = stackPeek!.next;
|
||||
stkSize--;
|
||||
return num;
|
||||
}
|
||||
|
||||
/* 訪問堆疊頂元素 */
|
||||
public int Peek() {
|
||||
if (IsEmpty())
|
||||
throw new Exception();
|
||||
return stackPeek!.val;
|
||||
}
|
||||
|
||||
/* 將 List 轉化為 Array 並返回 */
|
||||
public int[] ToArray() {
|
||||
if (stackPeek == null)
|
||||
return [];
|
||||
|
||||
ListNode? node = stackPeek;
|
||||
int[] res = new int[Size()];
|
||||
for (int i = res.Length - 1; i >= 0; i--) {
|
||||
res[i] = node!.val;
|
||||
node = node.next;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
public class linkedlist_stack {
|
||||
[Test]
|
||||
public void Test() {
|
||||
/* 初始化堆疊 */
|
||||
LinkedListStack stack = new();
|
||||
|
||||
/* 元素入堆疊 */
|
||||
stack.Push(1);
|
||||
stack.Push(3);
|
||||
stack.Push(2);
|
||||
stack.Push(5);
|
||||
stack.Push(4);
|
||||
Console.WriteLine("堆疊 stack = " + string.Join(",", stack.ToArray()));
|
||||
|
||||
/* 訪問堆疊頂元素 */
|
||||
int peek = stack.Peek();
|
||||
Console.WriteLine("堆疊頂元素 peek = " + peek);
|
||||
|
||||
/* 元素出堆疊 */
|
||||
int pop = stack.Pop();
|
||||
Console.WriteLine("出堆疊元素 pop = " + pop + ",出堆疊後 stack = " + string.Join(",", stack.ToArray()));
|
||||
|
||||
/* 獲取堆疊的長度 */
|
||||
int size = stack.Size();
|
||||
Console.WriteLine("堆疊的長度 size = " + size);
|
||||
|
||||
/* 判斷是否為空 */
|
||||
bool isEmpty = stack.IsEmpty();
|
||||
Console.WriteLine("堆疊是否為空 = " + isEmpty);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* File: queue.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_stack_and_queue;
|
||||
|
||||
public class queue {
|
||||
[Test]
|
||||
public void Test() {
|
||||
/* 初始化佇列 */
|
||||
Queue<int> queue = new();
|
||||
|
||||
/* 元素入列 */
|
||||
queue.Enqueue(1);
|
||||
queue.Enqueue(3);
|
||||
queue.Enqueue(2);
|
||||
queue.Enqueue(5);
|
||||
queue.Enqueue(4);
|
||||
Console.WriteLine("佇列 queue = " + string.Join(",", queue));
|
||||
|
||||
/* 訪問佇列首元素 */
|
||||
int peek = queue.Peek();
|
||||
Console.WriteLine("佇列首元素 peek = " + peek);
|
||||
|
||||
/* 元素出列 */
|
||||
int pop = queue.Dequeue();
|
||||
Console.WriteLine("出列元素 pop = " + pop + ",出列後 queue = " + string.Join(",", queue));
|
||||
|
||||
/* 獲取佇列的長度 */
|
||||
int size = queue.Count;
|
||||
Console.WriteLine("佇列長度 size = " + size);
|
||||
|
||||
/* 判斷佇列是否為空 */
|
||||
bool isEmpty = queue.Count == 0;
|
||||
Console.WriteLine("佇列是否為空 = " + isEmpty);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* File: stack.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_stack_and_queue;
|
||||
|
||||
public class stack {
|
||||
[Test]
|
||||
public void Test() {
|
||||
/* 初始化堆疊 */
|
||||
Stack<int> stack = new();
|
||||
|
||||
/* 元素入堆疊 */
|
||||
stack.Push(1);
|
||||
stack.Push(3);
|
||||
stack.Push(2);
|
||||
stack.Push(5);
|
||||
stack.Push(4);
|
||||
// 請注意,stack.ToArray() 得到的是倒序序列,即索引 0 為堆疊頂
|
||||
Console.WriteLine("堆疊 stack = " + string.Join(",", stack));
|
||||
|
||||
/* 訪問堆疊頂元素 */
|
||||
int peek = stack.Peek();
|
||||
Console.WriteLine("堆疊頂元素 peek = " + peek);
|
||||
|
||||
/* 元素出堆疊 */
|
||||
int pop = stack.Pop();
|
||||
Console.WriteLine("出堆疊元素 pop = " + pop + ",出堆疊後 stack = " + string.Join(",", stack));
|
||||
|
||||
/* 獲取堆疊的長度 */
|
||||
int size = stack.Count;
|
||||
Console.WriteLine("堆疊的長度 size = " + size);
|
||||
|
||||
/* 判斷是否為空 */
|
||||
bool isEmpty = stack.Count == 0;
|
||||
Console.WriteLine("堆疊是否為空 = " + isEmpty);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
/**
|
||||
* File: array_binary_tree.cs
|
||||
* Created Time: 2023-07-20
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_tree;
|
||||
|
||||
/* 陣列表示下的二元樹類別 */
|
||||
public class ArrayBinaryTree(List<int?> arr) {
|
||||
List<int?> tree = new(arr);
|
||||
|
||||
/* 串列容量 */
|
||||
public int Size() {
|
||||
return tree.Count;
|
||||
}
|
||||
|
||||
/* 獲取索引為 i 節點的值 */
|
||||
public int? Val(int i) {
|
||||
// 若索引越界,則返回 null ,代表空位
|
||||
if (i < 0 || i >= Size())
|
||||
return null;
|
||||
return tree[i];
|
||||
}
|
||||
|
||||
/* 獲取索引為 i 節點的左子節點的索引 */
|
||||
public int Left(int i) {
|
||||
return 2 * i + 1;
|
||||
}
|
||||
|
||||
/* 獲取索引為 i 節點的右子節點的索引 */
|
||||
public int Right(int i) {
|
||||
return 2 * i + 2;
|
||||
}
|
||||
|
||||
/* 獲取索引為 i 節點的父節點的索引 */
|
||||
public int Parent(int i) {
|
||||
return (i - 1) / 2;
|
||||
}
|
||||
|
||||
/* 層序走訪 */
|
||||
public List<int> LevelOrder() {
|
||||
List<int> res = [];
|
||||
// 直接走訪陣列
|
||||
for (int i = 0; i < Size(); i++) {
|
||||
if (Val(i).HasValue)
|
||||
res.Add(Val(i)!.Value);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* 深度優先走訪 */
|
||||
void DFS(int i, string order, List<int> res) {
|
||||
// 若為空位,則返回
|
||||
if (!Val(i).HasValue)
|
||||
return;
|
||||
// 前序走訪
|
||||
if (order == "pre")
|
||||
res.Add(Val(i)!.Value);
|
||||
DFS(Left(i), order, res);
|
||||
// 中序走訪
|
||||
if (order == "in")
|
||||
res.Add(Val(i)!.Value);
|
||||
DFS(Right(i), order, res);
|
||||
// 後序走訪
|
||||
if (order == "post")
|
||||
res.Add(Val(i)!.Value);
|
||||
}
|
||||
|
||||
/* 前序走訪 */
|
||||
public List<int> PreOrder() {
|
||||
List<int> res = [];
|
||||
DFS(0, "pre", res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* 中序走訪 */
|
||||
public List<int> InOrder() {
|
||||
List<int> res = [];
|
||||
DFS(0, "in", res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* 後序走訪 */
|
||||
public List<int> PostOrder() {
|
||||
List<int> res = [];
|
||||
DFS(0, "post", res);
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
public class array_binary_tree {
|
||||
[Test]
|
||||
public void Test() {
|
||||
// 初始化二元樹
|
||||
// 這裡藉助了一個從陣列直接生成二元樹的函式
|
||||
List<int?> arr = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15];
|
||||
|
||||
TreeNode? root = TreeNode.ListToTree(arr);
|
||||
Console.WriteLine("\n初始化二元樹\n");
|
||||
Console.WriteLine("二元樹的陣列表示:");
|
||||
Console.WriteLine(arr.PrintList());
|
||||
Console.WriteLine("二元樹的鏈結串列表示:");
|
||||
PrintUtil.PrintTree(root);
|
||||
|
||||
// 陣列表示下的二元樹類別
|
||||
ArrayBinaryTree abt = new(arr);
|
||||
|
||||
// 訪問節點
|
||||
int i = 1;
|
||||
int l = abt.Left(i);
|
||||
int r = abt.Right(i);
|
||||
int p = abt.Parent(i);
|
||||
Console.WriteLine("\n當前節點的索引為 " + i + " ,值為 " + abt.Val(i));
|
||||
Console.WriteLine("其左子節點的索引為 " + l + " ,值為 " + (abt.Val(l).HasValue ? abt.Val(l) : "null"));
|
||||
Console.WriteLine("其右子節點的索引為 " + r + " ,值為 " + (abt.Val(r).HasValue ? abt.Val(r) : "null"));
|
||||
Console.WriteLine("其父節點的索引為 " + p + " ,值為 " + (abt.Val(p).HasValue ? abt.Val(p) : "null"));
|
||||
|
||||
// 走訪樹
|
||||
List<int> res = abt.LevelOrder();
|
||||
Console.WriteLine("\n層序走訪為:" + res.PrintList());
|
||||
res = abt.PreOrder();
|
||||
Console.WriteLine("前序走訪為:" + res.PrintList());
|
||||
res = abt.InOrder();
|
||||
Console.WriteLine("中序走訪為:" + res.PrintList());
|
||||
res = abt.PostOrder();
|
||||
Console.WriteLine("後序走訪為:" + res.PrintList());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
/**
|
||||
* File: avl_tree.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_tree;
|
||||
|
||||
/* AVL 樹 */
|
||||
class AVLTree {
|
||||
public TreeNode? root; // 根節點
|
||||
|
||||
/* 獲取節點高度 */
|
||||
int Height(TreeNode? node) {
|
||||
// 空節點高度為 -1 ,葉節點高度為 0
|
||||
return node == null ? -1 : node.height;
|
||||
}
|
||||
|
||||
/* 更新節點高度 */
|
||||
void UpdateHeight(TreeNode node) {
|
||||
// 節點高度等於最高子樹高度 + 1
|
||||
node.height = Math.Max(Height(node.left), Height(node.right)) + 1;
|
||||
}
|
||||
|
||||
/* 獲取平衡因子 */
|
||||
public int BalanceFactor(TreeNode? node) {
|
||||
// 空節點平衡因子為 0
|
||||
if (node == null) return 0;
|
||||
// 節點平衡因子 = 左子樹高度 - 右子樹高度
|
||||
return Height(node.left) - Height(node.right);
|
||||
}
|
||||
|
||||
/* 右旋操作 */
|
||||
TreeNode? RightRotate(TreeNode? node) {
|
||||
TreeNode? child = node?.left;
|
||||
TreeNode? grandChild = child?.right;
|
||||
// 以 child 為原點,將 node 向右旋轉
|
||||
child.right = node;
|
||||
node.left = grandChild;
|
||||
// 更新節點高度
|
||||
UpdateHeight(node);
|
||||
UpdateHeight(child);
|
||||
// 返回旋轉後子樹的根節點
|
||||
return child;
|
||||
}
|
||||
|
||||
/* 左旋操作 */
|
||||
TreeNode? LeftRotate(TreeNode? node) {
|
||||
TreeNode? child = node?.right;
|
||||
TreeNode? grandChild = child?.left;
|
||||
// 以 child 為原點,將 node 向左旋轉
|
||||
child.left = node;
|
||||
node.right = grandChild;
|
||||
// 更新節點高度
|
||||
UpdateHeight(node);
|
||||
UpdateHeight(child);
|
||||
// 返回旋轉後子樹的根節點
|
||||
return child;
|
||||
}
|
||||
|
||||
/* 執行旋轉操作,使該子樹重新恢復平衡 */
|
||||
TreeNode? Rotate(TreeNode? node) {
|
||||
// 獲取節點 node 的平衡因子
|
||||
int balanceFactorInt = BalanceFactor(node);
|
||||
// 左偏樹
|
||||
if (balanceFactorInt > 1) {
|
||||
if (BalanceFactor(node?.left) >= 0) {
|
||||
// 右旋
|
||||
return RightRotate(node);
|
||||
} else {
|
||||
// 先左旋後右旋
|
||||
node!.left = LeftRotate(node!.left);
|
||||
return RightRotate(node);
|
||||
}
|
||||
}
|
||||
// 右偏樹
|
||||
if (balanceFactorInt < -1) {
|
||||
if (BalanceFactor(node?.right) <= 0) {
|
||||
// 左旋
|
||||
return LeftRotate(node);
|
||||
} else {
|
||||
// 先右旋後左旋
|
||||
node!.right = RightRotate(node!.right);
|
||||
return LeftRotate(node);
|
||||
}
|
||||
}
|
||||
// 平衡樹,無須旋轉,直接返回
|
||||
return node;
|
||||
}
|
||||
|
||||
/* 插入節點 */
|
||||
public void Insert(int val) {
|
||||
root = InsertHelper(root, val);
|
||||
}
|
||||
|
||||
/* 遞迴插入節點(輔助方法) */
|
||||
TreeNode? InsertHelper(TreeNode? node, int val) {
|
||||
if (node == null) return new TreeNode(val);
|
||||
/* 1. 查詢插入位置並插入節點 */
|
||||
if (val < node.val)
|
||||
node.left = InsertHelper(node.left, val);
|
||||
else if (val > node.val)
|
||||
node.right = InsertHelper(node.right, val);
|
||||
else
|
||||
return node; // 重複節點不插入,直接返回
|
||||
UpdateHeight(node); // 更新節點高度
|
||||
/* 2. 執行旋轉操作,使該子樹重新恢復平衡 */
|
||||
node = Rotate(node);
|
||||
// 返回子樹的根節點
|
||||
return node;
|
||||
}
|
||||
|
||||
/* 刪除節點 */
|
||||
public void Remove(int val) {
|
||||
root = RemoveHelper(root, val);
|
||||
}
|
||||
|
||||
/* 遞迴刪除節點(輔助方法) */
|
||||
TreeNode? RemoveHelper(TreeNode? node, int val) {
|
||||
if (node == null) return null;
|
||||
/* 1. 查詢節點並刪除 */
|
||||
if (val < node.val)
|
||||
node.left = RemoveHelper(node.left, val);
|
||||
else if (val > node.val)
|
||||
node.right = RemoveHelper(node.right, val);
|
||||
else {
|
||||
if (node.left == null || node.right == null) {
|
||||
TreeNode? child = node.left ?? node.right;
|
||||
// 子節點數量 = 0 ,直接刪除 node 並返回
|
||||
if (child == null)
|
||||
return null;
|
||||
// 子節點數量 = 1 ,直接刪除 node
|
||||
else
|
||||
node = child;
|
||||
} else {
|
||||
// 子節點數量 = 2 ,則將中序走訪的下個節點刪除,並用該節點替換當前節點
|
||||
TreeNode? temp = node.right;
|
||||
while (temp.left != null) {
|
||||
temp = temp.left;
|
||||
}
|
||||
node.right = RemoveHelper(node.right, temp.val!.Value);
|
||||
node.val = temp.val;
|
||||
}
|
||||
}
|
||||
UpdateHeight(node); // 更新節點高度
|
||||
/* 2. 執行旋轉操作,使該子樹重新恢復平衡 */
|
||||
node = Rotate(node);
|
||||
// 返回子樹的根節點
|
||||
return node;
|
||||
}
|
||||
|
||||
/* 查詢節點 */
|
||||
public TreeNode? Search(int val) {
|
||||
TreeNode? cur = root;
|
||||
// 迴圈查詢,越過葉節點後跳出
|
||||
while (cur != null) {
|
||||
// 目標節點在 cur 的右子樹中
|
||||
if (cur.val < val)
|
||||
cur = cur.right;
|
||||
// 目標節點在 cur 的左子樹中
|
||||
else if (cur.val > val)
|
||||
cur = cur.left;
|
||||
// 找到目標節點,跳出迴圈
|
||||
else
|
||||
break;
|
||||
}
|
||||
// 返回目標節點
|
||||
return cur;
|
||||
}
|
||||
}
|
||||
|
||||
public class avl_tree {
|
||||
static void TestInsert(AVLTree tree, int val) {
|
||||
tree.Insert(val);
|
||||
Console.WriteLine("\n插入節點 " + val + " 後,AVL 樹為");
|
||||
PrintUtil.PrintTree(tree.root);
|
||||
}
|
||||
|
||||
static void TestRemove(AVLTree tree, int val) {
|
||||
tree.Remove(val);
|
||||
Console.WriteLine("\n刪除節點 " + val + " 後,AVL 樹為");
|
||||
PrintUtil.PrintTree(tree.root);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
/* 初始化空 AVL 樹 */
|
||||
AVLTree avlTree = new();
|
||||
|
||||
/* 插入節點 */
|
||||
// 請關注插入節點後,AVL 樹是如何保持平衡的
|
||||
TestInsert(avlTree, 1);
|
||||
TestInsert(avlTree, 2);
|
||||
TestInsert(avlTree, 3);
|
||||
TestInsert(avlTree, 4);
|
||||
TestInsert(avlTree, 5);
|
||||
TestInsert(avlTree, 8);
|
||||
TestInsert(avlTree, 7);
|
||||
TestInsert(avlTree, 9);
|
||||
TestInsert(avlTree, 10);
|
||||
TestInsert(avlTree, 6);
|
||||
|
||||
/* 插入重複節點 */
|
||||
TestInsert(avlTree, 7);
|
||||
|
||||
/* 刪除節點 */
|
||||
// 請關注刪除節點後,AVL 樹是如何保持平衡的
|
||||
TestRemove(avlTree, 8); // 刪除度為 0 的節點
|
||||
TestRemove(avlTree, 5); // 刪除度為 1 的節點
|
||||
TestRemove(avlTree, 4); // 刪除度為 2 的節點
|
||||
|
||||
/* 查詢節點 */
|
||||
TreeNode? node = avlTree.Search(7);
|
||||
Console.WriteLine("\n查詢到的節點物件為 " + node + ",節點值 = " + node?.val);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* File: binary_search_tree.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_tree;
|
||||
|
||||
class BinarySearchTree {
|
||||
TreeNode? root;
|
||||
|
||||
public BinarySearchTree() {
|
||||
// 初始化空樹
|
||||
root = null;
|
||||
}
|
||||
|
||||
/* 獲取二元樹根節點 */
|
||||
public TreeNode? GetRoot() {
|
||||
return root;
|
||||
}
|
||||
|
||||
/* 查詢節點 */
|
||||
public TreeNode? Search(int num) {
|
||||
TreeNode? cur = root;
|
||||
// 迴圈查詢,越過葉節點後跳出
|
||||
while (cur != null) {
|
||||
// 目標節點在 cur 的右子樹中
|
||||
if (cur.val < num) cur =
|
||||
cur.right;
|
||||
// 目標節點在 cur 的左子樹中
|
||||
else if (cur.val > num)
|
||||
cur = cur.left;
|
||||
// 找到目標節點,跳出迴圈
|
||||
else
|
||||
break;
|
||||
}
|
||||
// 返回目標節點
|
||||
return cur;
|
||||
}
|
||||
|
||||
/* 插入節點 */
|
||||
public void Insert(int num) {
|
||||
// 若樹為空,則初始化根節點
|
||||
if (root == null) {
|
||||
root = new TreeNode(num);
|
||||
return;
|
||||
}
|
||||
TreeNode? cur = root, pre = null;
|
||||
// 迴圈查詢,越過葉節點後跳出
|
||||
while (cur != null) {
|
||||
// 找到重複節點,直接返回
|
||||
if (cur.val == num)
|
||||
return;
|
||||
pre = cur;
|
||||
// 插入位置在 cur 的右子樹中
|
||||
if (cur.val < num)
|
||||
cur = cur.right;
|
||||
// 插入位置在 cur 的左子樹中
|
||||
else
|
||||
cur = cur.left;
|
||||
}
|
||||
|
||||
// 插入節點
|
||||
TreeNode node = new(num);
|
||||
if (pre != null) {
|
||||
if (pre.val < num)
|
||||
pre.right = node;
|
||||
else
|
||||
pre.left = node;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* 刪除節點 */
|
||||
public void Remove(int num) {
|
||||
// 若樹為空,直接提前返回
|
||||
if (root == null)
|
||||
return;
|
||||
TreeNode? cur = root, pre = null;
|
||||
// 迴圈查詢,越過葉節點後跳出
|
||||
while (cur != null) {
|
||||
// 找到待刪除節點,跳出迴圈
|
||||
if (cur.val == num)
|
||||
break;
|
||||
pre = cur;
|
||||
// 待刪除節點在 cur 的右子樹中
|
||||
if (cur.val < num)
|
||||
cur = cur.right;
|
||||
// 待刪除節點在 cur 的左子樹中
|
||||
else
|
||||
cur = cur.left;
|
||||
}
|
||||
// 若無待刪除節點,則直接返回
|
||||
if (cur == null)
|
||||
return;
|
||||
// 子節點數量 = 0 or 1
|
||||
if (cur.left == null || cur.right == null) {
|
||||
// 當子節點數量 = 0 / 1 時, child = null / 該子節點
|
||||
TreeNode? child = cur.left ?? cur.right;
|
||||
// 刪除節點 cur
|
||||
if (cur != root) {
|
||||
if (pre!.left == cur)
|
||||
pre.left = child;
|
||||
else
|
||||
pre.right = child;
|
||||
} else {
|
||||
// 若刪除節點為根節點,則重新指定根節點
|
||||
root = child;
|
||||
}
|
||||
}
|
||||
// 子節點數量 = 2
|
||||
else {
|
||||
// 獲取中序走訪中 cur 的下一個節點
|
||||
TreeNode? tmp = cur.right;
|
||||
while (tmp.left != null) {
|
||||
tmp = tmp.left;
|
||||
}
|
||||
// 遞迴刪除節點 tmp
|
||||
Remove(tmp.val!.Value);
|
||||
// 用 tmp 覆蓋 cur
|
||||
cur.val = tmp.val;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class binary_search_tree {
|
||||
[Test]
|
||||
public void Test() {
|
||||
/* 初始化二元搜尋樹 */
|
||||
BinarySearchTree bst = new();
|
||||
// 請注意,不同的插入順序會生成不同的二元樹,該序列可以生成一個完美二元樹
|
||||
int[] nums = [8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15];
|
||||
foreach (int num in nums) {
|
||||
bst.Insert(num);
|
||||
}
|
||||
|
||||
Console.WriteLine("\n初始化的二元樹為\n");
|
||||
PrintUtil.PrintTree(bst.GetRoot());
|
||||
|
||||
/* 查詢節點 */
|
||||
TreeNode? node = bst.Search(7);
|
||||
Console.WriteLine("\n查詢到的節點物件為 " + node + ",節點值 = " + node?.val);
|
||||
|
||||
/* 插入節點 */
|
||||
bst.Insert(16);
|
||||
Console.WriteLine("\n插入節點 16 後,二元樹為\n");
|
||||
PrintUtil.PrintTree(bst.GetRoot());
|
||||
|
||||
/* 刪除節點 */
|
||||
bst.Remove(1);
|
||||
Console.WriteLine("\n刪除節點 1 後,二元樹為\n");
|
||||
PrintUtil.PrintTree(bst.GetRoot());
|
||||
bst.Remove(2);
|
||||
Console.WriteLine("\n刪除節點 2 後,二元樹為\n");
|
||||
PrintUtil.PrintTree(bst.GetRoot());
|
||||
bst.Remove(4);
|
||||
Console.WriteLine("\n刪除節點 4 後,二元樹為\n");
|
||||
PrintUtil.PrintTree(bst.GetRoot());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* File: binary_tree.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_tree;
|
||||
|
||||
public class binary_tree {
|
||||
[Test]
|
||||
public void Test() {
|
||||
/* 初始化二元樹 */
|
||||
// 初始化節點
|
||||
TreeNode n1 = new(1);
|
||||
TreeNode n2 = new(2);
|
||||
TreeNode n3 = new(3);
|
||||
TreeNode n4 = new(4);
|
||||
TreeNode n5 = new(5);
|
||||
// 構建節點之間的引用(指標)
|
||||
n1.left = n2;
|
||||
n1.right = n3;
|
||||
n2.left = n4;
|
||||
n2.right = n5;
|
||||
Console.WriteLine("\n初始化二元樹\n");
|
||||
PrintUtil.PrintTree(n1);
|
||||
|
||||
/* 插入與刪除節點 */
|
||||
TreeNode P = new(0);
|
||||
// 在 n1 -> n2 中間插入節點 P
|
||||
n1.left = P;
|
||||
P.left = n2;
|
||||
Console.WriteLine("\n插入節點 P 後\n");
|
||||
PrintUtil.PrintTree(n1);
|
||||
// 刪除節點 P
|
||||
n1.left = n2;
|
||||
Console.WriteLine("\n刪除節點 P 後\n");
|
||||
PrintUtil.PrintTree(n1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* File: binary_tree_bfs.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_tree;
|
||||
|
||||
public class binary_tree_bfs {
|
||||
|
||||
/* 層序走訪 */
|
||||
List<int> LevelOrder(TreeNode root) {
|
||||
// 初始化佇列,加入根節點
|
||||
Queue<TreeNode> queue = new();
|
||||
queue.Enqueue(root);
|
||||
// 初始化一個串列,用於儲存走訪序列
|
||||
List<int> list = [];
|
||||
while (queue.Count != 0) {
|
||||
TreeNode node = queue.Dequeue(); // 隊列出隊
|
||||
list.Add(node.val!.Value); // 儲存節點值
|
||||
if (node.left != null)
|
||||
queue.Enqueue(node.left); // 左子節點入列
|
||||
if (node.right != null)
|
||||
queue.Enqueue(node.right); // 右子節點入列
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
/* 初始化二元樹 */
|
||||
// 這裡藉助了一個從陣列直接生成二元樹的函式
|
||||
TreeNode? root = TreeNode.ListToTree([1, 2, 3, 4, 5, 6, 7]);
|
||||
Console.WriteLine("\n初始化二元樹\n");
|
||||
PrintUtil.PrintTree(root);
|
||||
|
||||
List<int> list = LevelOrder(root!);
|
||||
Console.WriteLine("\n層序走訪的節點列印序列 = " + string.Join(",", list));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* File: binary_tree_dfs.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_tree;
|
||||
|
||||
public class binary_tree_dfs {
|
||||
List<int> list = [];
|
||||
|
||||
/* 前序走訪 */
|
||||
void PreOrder(TreeNode? root) {
|
||||
if (root == null) return;
|
||||
// 訪問優先順序:根節點 -> 左子樹 -> 右子樹
|
||||
list.Add(root.val!.Value);
|
||||
PreOrder(root.left);
|
||||
PreOrder(root.right);
|
||||
}
|
||||
|
||||
/* 中序走訪 */
|
||||
void InOrder(TreeNode? root) {
|
||||
if (root == null) return;
|
||||
// 訪問優先順序:左子樹 -> 根節點 -> 右子樹
|
||||
InOrder(root.left);
|
||||
list.Add(root.val!.Value);
|
||||
InOrder(root.right);
|
||||
}
|
||||
|
||||
/* 後序走訪 */
|
||||
void PostOrder(TreeNode? root) {
|
||||
if (root == null) return;
|
||||
// 訪問優先順序:左子樹 -> 右子樹 -> 根節點
|
||||
PostOrder(root.left);
|
||||
PostOrder(root.right);
|
||||
list.Add(root.val!.Value);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
/* 初始化二元樹 */
|
||||
// 這裡藉助了一個從陣列直接生成二元樹的函式
|
||||
TreeNode? root = TreeNode.ListToTree([1, 2, 3, 4, 5, 6, 7]);
|
||||
Console.WriteLine("\n初始化二元樹\n");
|
||||
PrintUtil.PrintTree(root);
|
||||
|
||||
list.Clear();
|
||||
PreOrder(root);
|
||||
Console.WriteLine("\n前序走訪的節點列印序列 = " + string.Join(",", list));
|
||||
|
||||
list.Clear();
|
||||
InOrder(root);
|
||||
Console.WriteLine("\n中序走訪的節點列印序列 = " + string.Join(",", list));
|
||||
|
||||
list.Clear();
|
||||
PostOrder(root);
|
||||
Console.WriteLine("\n後序走訪的節點列印序列 = " + string.Join(",", list));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.5.002.0
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "hello-algo", "hello-algo.csproj", "{48B60439-EFDC-4C8F-AE8D-41979958C8AC}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{48B60439-EFDC-4C8F-AE8D-41979958C8AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{48B60439-EFDC-4C8F-AE8D-41979958C8AC}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{48B60439-EFDC-4C8F-AE8D-41979958C8AC}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{48B60439-EFDC-4C8F-AE8D-41979958C8AC}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {1E773F8A-FF66-4974-820B-FCE9032D19AE}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -0,0 +1,21 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<RootNamespace>hello_algo</RootNamespace>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
|
||||
<PackageReference Include="NUnit" Version="3.14.0" />
|
||||
<PackageReference Include="NUnit3TestAdapter" Version="4.5.0" />
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.0">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,32 @@
|
||||
// File: ListNode.cs
|
||||
// Created Time: 2022-12-16
|
||||
// Author: mingXta (1195669834@qq.com)
|
||||
|
||||
namespace hello_algo.utils;
|
||||
|
||||
/* 鏈結串列節點 */
|
||||
public class ListNode(int x) {
|
||||
public int val = x;
|
||||
public ListNode? next;
|
||||
|
||||
/* 將陣列反序列化為鏈結串列 */
|
||||
public static ListNode? ArrToLinkedList(int[] arr) {
|
||||
ListNode dum = new(0);
|
||||
ListNode head = dum;
|
||||
foreach (int val in arr) {
|
||||
head.next = new ListNode(val);
|
||||
head = head.next;
|
||||
}
|
||||
return dum.next;
|
||||
}
|
||||
|
||||
public override string? ToString() {
|
||||
List<string> list = [];
|
||||
var head = this;
|
||||
while (head != null) {
|
||||
list.Add(head.val.ToString());
|
||||
head = head.next;
|
||||
}
|
||||
return string.Join("->", list);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
/**
|
||||
* File: PrintUtil.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com), krahets (krahets@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.utils;
|
||||
|
||||
public class Trunk(Trunk? prev, string str) {
|
||||
public Trunk? prev = prev;
|
||||
public string str = str;
|
||||
};
|
||||
|
||||
public static class PrintUtil {
|
||||
/* 列印串列 */
|
||||
public static void PrintList<T>(IList<T> list) {
|
||||
Console.WriteLine("[" + string.Join(", ", list) + "]");
|
||||
}
|
||||
|
||||
public static string PrintList<T>(this IEnumerable<T?> list) {
|
||||
return $"[ {string.Join(", ", list.Select(x => x?.ToString() ?? "null"))} ]";
|
||||
}
|
||||
|
||||
/* 列印矩陣 (Array) */
|
||||
public static void PrintMatrix<T>(T[][] matrix) {
|
||||
Console.WriteLine("[");
|
||||
foreach (T[] row in matrix) {
|
||||
Console.WriteLine(" " + string.Join(", ", row) + ",");
|
||||
}
|
||||
Console.WriteLine("]");
|
||||
}
|
||||
|
||||
/* 列印矩陣 (List) */
|
||||
public static void PrintMatrix<T>(List<List<T>> matrix) {
|
||||
Console.WriteLine("[");
|
||||
foreach (List<T> row in matrix) {
|
||||
Console.WriteLine(" " + string.Join(", ", row) + ",");
|
||||
}
|
||||
Console.WriteLine("]");
|
||||
}
|
||||
|
||||
/* 列印鏈結串列 */
|
||||
public static void PrintLinkedList(ListNode? head) {
|
||||
List<string> list = [];
|
||||
while (head != null) {
|
||||
list.Add(head.val.ToString());
|
||||
head = head.next;
|
||||
}
|
||||
Console.Write(string.Join(" -> ", list));
|
||||
}
|
||||
|
||||
/**
|
||||
* 列印二元樹
|
||||
* This tree printer is borrowed from TECHIE DELIGHT
|
||||
* https://www.techiedelight.com/c-program-print-binary-tree/
|
||||
*/
|
||||
public static void PrintTree(TreeNode? root) {
|
||||
PrintTree(root, null, false);
|
||||
}
|
||||
|
||||
/* 列印二元樹 */
|
||||
public static void PrintTree(TreeNode? root, Trunk? prev, bool isRight) {
|
||||
if (root == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
string prev_str = " ";
|
||||
Trunk trunk = new(prev, prev_str);
|
||||
|
||||
PrintTree(root.right, trunk, true);
|
||||
|
||||
if (prev == null) {
|
||||
trunk.str = "———";
|
||||
} else if (isRight) {
|
||||
trunk.str = "/———";
|
||||
prev_str = " |";
|
||||
} else {
|
||||
trunk.str = "\\———";
|
||||
prev.str = prev_str;
|
||||
}
|
||||
|
||||
ShowTrunks(trunk);
|
||||
Console.WriteLine(" " + root.val);
|
||||
|
||||
if (prev != null) {
|
||||
prev.str = prev_str;
|
||||
}
|
||||
trunk.str = " |";
|
||||
|
||||
PrintTree(root.left, trunk, false);
|
||||
}
|
||||
|
||||
public static void ShowTrunks(Trunk? p) {
|
||||
if (p == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
ShowTrunks(p.prev);
|
||||
Console.Write(p.str);
|
||||
}
|
||||
|
||||
/* 列印雜湊表 */
|
||||
public static void PrintHashMap<K, V>(Dictionary<K, V> map) where K : notnull {
|
||||
foreach (var kv in map.Keys) {
|
||||
Console.WriteLine(kv.ToString() + " -> " + map[kv]?.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
/* 列印堆積 */
|
||||
public static void PrintHeap(Queue<int> queue) {
|
||||
Console.Write("堆積的陣列表示:");
|
||||
List<int> list = [.. queue];
|
||||
Console.WriteLine(string.Join(',', list));
|
||||
Console.WriteLine("堆積的樹狀表示:");
|
||||
TreeNode? tree = TreeNode.ListToTree(list.Cast<int?>().ToList());
|
||||
PrintTree(tree);
|
||||
}
|
||||
|
||||
/* 列印優先佇列 */
|
||||
public static void PrintHeap(PriorityQueue<int, int> queue) {
|
||||
var newQueue = new PriorityQueue<int, int>(queue.UnorderedItems, queue.Comparer);
|
||||
Console.Write("堆積的陣列表示:");
|
||||
List<int> list = [];
|
||||
while (newQueue.TryDequeue(out int element, out _)) {
|
||||
list.Add(element);
|
||||
}
|
||||
Console.WriteLine("堆積的樹狀表示:");
|
||||
Console.WriteLine(string.Join(',', list.ToList()));
|
||||
TreeNode? tree = TreeNode.ListToTree(list.Cast<int?>().ToList());
|
||||
PrintTree(tree);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* File: TreeNode.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.utils;
|
||||
|
||||
/* 二元樹節點類別 */
|
||||
public class TreeNode(int? x) {
|
||||
public int? val = x; // 節點值
|
||||
public int height; // 節點高度
|
||||
public TreeNode? left; // 左子節點引用
|
||||
public TreeNode? right; // 右子節點引用
|
||||
|
||||
// 序列化編碼規則請參考:
|
||||
// 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
|
||||
|
||||
/* 將串列反序列化為二元樹:遞迴 */
|
||||
static TreeNode? ListToTreeDFS(List<int?> arr, int i) {
|
||||
if (i < 0 || i >= arr.Count || !arr[i].HasValue) {
|
||||
return null;
|
||||
}
|
||||
TreeNode root = new(arr[i]) {
|
||||
left = ListToTreeDFS(arr, 2 * i + 1),
|
||||
right = ListToTreeDFS(arr, 2 * i + 2)
|
||||
};
|
||||
return root;
|
||||
}
|
||||
|
||||
/* 將串列反序列化為二元樹 */
|
||||
public static TreeNode? ListToTree(List<int?> arr) {
|
||||
return ListToTreeDFS(arr, 0);
|
||||
}
|
||||
|
||||
/* 將二元樹序列化為串列:遞迴 */
|
||||
static void TreeToListDFS(TreeNode? root, int i, List<int?> res) {
|
||||
if (root == null)
|
||||
return;
|
||||
while (i >= res.Count) {
|
||||
res.Add(null);
|
||||
}
|
||||
res[i] = root.val;
|
||||
TreeToListDFS(root.left, 2 * i + 1, res);
|
||||
TreeToListDFS(root.right, 2 * i + 2, res);
|
||||
}
|
||||
|
||||
/* 將二元樹序列化為串列 */
|
||||
public static List<int?> TreeToList(TreeNode root) {
|
||||
List<int?> res = [];
|
||||
TreeToListDFS(root, 0, res);
|
||||
return res;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* File: Vertex.cs
|
||||
* Created Time: 2023-02-06
|
||||
* Author: zjkung1123 (zjkung1123@gmail.com), krahets (krahets@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.utils;
|
||||
|
||||
/* 頂點類別 */
|
||||
public class Vertex(int val) {
|
||||
public int val = val;
|
||||
|
||||
/* 輸入值串列 vals ,返回頂點串列 vets */
|
||||
public static Vertex[] ValsToVets(int[] vals) {
|
||||
Vertex[] vets = new Vertex[vals.Length];
|
||||
for (int i = 0; i < vals.Length; i++) {
|
||||
vets[i] = new Vertex(vals[i]);
|
||||
}
|
||||
return vets;
|
||||
}
|
||||
|
||||
/* 輸入頂點串列 vets ,返回值串列 vals */
|
||||
public static List<int> VetsToVals(List<Vertex> vets) {
|
||||
List<int> vals = [];
|
||||
foreach (Vertex vet in vets) {
|
||||
vals.Add(vet.val);
|
||||
}
|
||||
return vals;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user