Compare commits

...

191 Commits
1.1.0 ... main

Author SHA1 Message Date
rongyi 0918fd06f2
polish rust (#1790)
* polish graph

* Update graph
2025-08-04 14:45:14 +08:00
WuJing 83a806a602
greedy/max_capacity: fix myMax algorithm error (#1784)
Co-authored-by: wujing <realwujing@qq.com>
2025-07-21 15:12:34 +08:00
sunshinesDL 5c085b5592
Update performance_evaluation.md (#1770)
* Update performance_evaluation.md

**修改内容:**
把本节使用的 “输入数据大小” 统一修改为 “输入数据规模”。

**修改原因:**
今天在分析一个函数的复杂度时回看本节,发现这处表述好像存在歧义。阅读本节内容可知,复杂度分析实际是分析算法的运行时间和空间占用与数据规模的关系。 从字面理解,“输入数据的大小” 更像指输入数据的数值大小,而非数据规模。虽然多数场景下,输入数据的数值大小可以通过迭代/递归反映数据规模,但在个别场景下并非如此,如 5.1.2 节 "基于链表实现的栈" 中的 `to_list() `函数:
```python
 def to_list(self) -> list[int]:
        """转化为列表用于打印"""
        arr = []
        node = self._peek
        while node:
            arr.append(node.val)
            node = node.next
        arr.reverse()
        return arr
```
该函数无形参,其时间复杂度实际指,函数运行时间随着栈中数据数量的增加而呈现的增长趋势,而非随栈中数据数值大小的增加呈现的增长趋势。 因此,为规避歧义,小白提议将本节的“输入数据大小” 改为 “输入数据规模”。

然而,一百个读者有一百个哈姆雷特,或许其他读者读到这里未感觉歧义,且本章后续章节还有多处使用这一表述,若本节修改可能后面也需与其保持统一。或许也可以在本章2.1节插入一个Tip约定这一表述的实际意义。考虑不周,欢迎 K大及评阅大佬指正!

* Update performance_evaluation.md

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2025-07-20 19:56:15 +08:00
sunshinesDL ee4d27dc17
Update time_complexity.md (#1772)
* Update time_complexity.md

对于多项式函数 c * f(n), 系数 c 好像不能称为常数项,遂查阅《算法导论 第三版》相关章节,在其 26 页使用了常量因子这一表述,该表述好像晦涩了些,小白提议这里将 ”常数项“ 改为 ”常数“。 
欢迎 K大及评阅大佬指正!

* Update time_complexity.md

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2025-07-10 07:08:44 +08:00
Beatrix CHAN 301adcf416
translation: Update algorithms_are_everywhere.md (#1733)
* Improve English Translation for algorithms_are_everywhere.md

* Fixed line 5, 7, 10

* Keep initial alt text for binary search demonstration

* Update Example 3 English translation

* Update algorithms_are_everywhere.md

* Update algorithms_are_everywhere.md

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2025-07-10 06:54:30 +08:00
Magenta Qin f47d371035
translation: Update EN translation for Introduction Chapter (#1739)
* doc: update en translation of algorithm_are_everywhere

* doc: update en translation of what_is_dsa

* doc: update en translation of summary

* feat: en translation for Q&A

* doc: update en translation to make it more concise

* Update algorithms_are_everywhere.md

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2025-07-10 06:38:30 +08:00
Magenta Qin e058e14253
translation: Update en translation for preface (#1738)
* doc: update en translation for preface

* doc: fix blank line and other typos

* doc: fix period
2025-07-10 06:36:16 +08:00
rongyi b0c147b67c
Polish rust (#1777)
* Polish rust

* Update array queue and linkedlist queue

* Update linkedlist deque

* make array deque generic
2025-07-10 06:33:22 +08:00
Yudong Jin e8dc4736a2
Bug fixes and improvements. (#1780)
* Fix the "尾递归优化" to "递归深度优化" in quick_sort.

* Update landing pages.

* Sync zh and zh-hant versions.

* Sync zh and zh-hant versions.
2025-07-10 06:32:25 +08:00
sunshinesDL 6a4d62449c
Update max_product_cutting_problem.md (#1758)
* Update max_product_cutting_problem.md

本节结尾的正确性证明中,

"使用反证法,只分析 n >= 3 的情况。"

这句是否应该改为 “只分析 n >= 4 的情况”,因为 n == 3 时,由于题目要求至少将 n 切分为两个正整数,所以此时应该切分为 1 * 2 ,切分方案里是包含 1 的 😁;
此外,对于这句描述:

“假设最优切分方案中存在 >= 4 的因子 x ,那么一定可以将其继续划分为 2(x-2) ,从而获得更大的乘积。”

最后半句改为“从而获得更大或可替代的乘积”是否更好,因为当切分方案中存在 4 作为因子时,将其划分为 2 * 2,乘积相对划分前是相等的。不过这处改动不影响“所有因子 <= 3” 的结论,因为因子 4 是可以被替代的。

* Update max_product_cutting_problem.md

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2025-06-12 21:10:15 +08:00
Dr.XYZ ceec0eaa3a
Specify currency unit in the "Price" row of the storage compar… (#1755)
* Specify currency unit as CNY in the "Price" row of the storage comparison table

* Revert changes to the English version

* Change currency unit to USD

* fix

* fix space

* Update ram_and_cache.md

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2025-06-12 20:57:47 +08:00
rongyi 7751ea1256
update rust heap (#1761) 2025-06-12 20:47:47 +08:00
Seven Du 5a4aa8c554
en: fix picture file name (#1764) 2025-06-12 20:46:31 +08:00
Yudong Jin db64108e5d
Bug fixes (#1766)
* Sync zh and zh-hant versions.

* Bug fixes.
2025-06-12 20:45:41 +08:00
砖吐筷筷 f42cec0f88
fix(graph): enhance the judgment of boundary conditions for removeEdge functions (#1412) 2025-05-17 17:26:38 +08:00
Asashishi_Nyan! 09f7223067
optimized the js api use of counting_sort chapter for Math.max() (#1748)
* Update counting_sort.ts optimized the Math.max

* Update counting_sort.ts

* Update counting_sort.js

* Update radix_sort.ts

* Update radix_sort.js
2025-05-17 17:17:22 +08:00
Seren e79a56f540
Update Zig example code (#1737) 2025-05-17 17:15:30 +08:00
UMER JAHANGIR e4f5787685
Translation: Update intro_to_dynamic_programming.md (#1751)
* Update intro_to_dynamic_programming.md

* Update intro_to_dynamic_programming.md

Made corrections and improvements to the introduction of dynamic programming based on reviewer suggestions.

* Update intro_to_dynamic_programming.md

Again, I made corrections and improvements to the introduction of dynamic programming based on reviewer suggestions.

* Update intro_to_dynamic_programming.md

chore: corrected missed feedback/suggestion from review
2025-05-17 17:14:43 +08:00
趙子賢 3ad70167db
Fix typo in Traditional Chinese translation of binary search (#1750)
線上性查詢 -> 線性查詢
2025-05-17 17:14:32 +08:00
Yudong Jin f9d37e0d16
Update en/README. Bug fixes. (#1742)
* Fix graph_operations.md

* Update README

* Sync zh and zh-hant versions.
2025-04-27 16:56:24 +08:00
Yudong Jin 1904bb8afc
Add origins in giscus.json. Update en/README.md. (#1740)
* Fix the definition of "complete binary tree" in binary_tree.md

* Update en/README.md

* Add origins in giscus.json
2025-04-27 16:07:22 +08:00
Colin Penn e1f0903bf7
translation: Update n_queens_problem.md (#1676)
* Update n_queens_problem.md

* translation: Update n_queens_problem.md
2025-04-26 00:47:07 +08:00
Colin Penn cc0852fae8
translation: update chapter_backtracking/summary.md (#1671)
* update chapter_backtracking/summary.md

* translation: update chapter_backtracking/summary.md

* translation: update chapter_backtracking/summary.md
2025-04-26 00:46:10 +08:00
Thomas 9997c2822c
translation: backtracking algorithm (#1669)
* translation: backtracking algorithm

* resolve comments
2025-04-26 00:45:01 +08:00
Yudong Jin d976116292
Bug fixes and improvements (#1735)
* Fix the definition of "complete binary tree" in binary_tree.md

* Update en/README.md
2025-04-15 16:57:31 +08:00
Yudong Jin 8e38c61455
Bug fixes and improvements (#1732)
* Bug fixes

* Sync zh and zh-hant versions.

* "入列列" -> "入佇列"

* Fix hello_algo_mindmap.png
2025-04-10 19:21:52 +08:00
Ian Chiu a9d44c3a25
fix(zh-hant translation): graph_traversal.md (#1711)
* 修正 graph_traversal.md 繁體中文版錯誤的文字

`列列` -> `隊列`

* Update graph_traversal.md

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2025-03-28 17:09:29 +08:00
Sizhe Fan 3177d35eb2
Update the description of time and space complexity of fractional_knapsack problem. (#1688)
* 优化分数背包的部分复杂度描述,使其更加严谨

* Update fractional_knapsack_problem.md

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2025-03-20 19:46:17 +08:00
Phoenix Xie 1db2001e9b
tanslation: Update chapter_backtracking / permutations_problem.md (#1664)
* tanslation: Update chapter_backtracking / permutations_problem.md

* Update permutations_problem.md

* Update permutations_problem.md

* Update permutations_problem.md

* Update permutations_problem.md

* Update permutations_problem.md
2025-03-14 17:56:41 +08:00
Yudong Jin 0a3d3940c4
Merge pull request #1681 from rongyi/main
tiny fix, more readable rust
2025-03-11 16:56:33 +08:00
rongyi bd03b8c66e tiny fix, more readable rust 2025-03-10 17:22:06 +08:00
Red Wood 7e904c8ff6
Update counting_sort.py (#1677)
Since the max function is called to find the maximum value, it doesn't seem necessary to traverse the list and call the max function several times to select the larger value.
2025-03-09 06:39:32 +08:00
Peng Chen 82fa8cb222
Fix the typo in backtracking/summary.md (#1673) 2025-03-09 06:36:17 +08:00
Phoenix Xie f45f847742
translation: Update chatpter_dynamic_programming / index.md (#1668)
* translation: Update chatpter_dynamic_programming / index.md

* Update index.md
2025-03-09 06:35:04 +08:00
Phoenix Xie 8e3b795599
translation: chapter_divide_and _conquer / Update hanota_problem.md (#1657)
* translation: chapter_divide_and _conquer / Update hanota_problem.md

* Update hanota_problem.md

* Update hanota_problem.md
2025-03-09 06:33:14 +08:00
Phoenix Xie 59bd843953
translation: Update chapter_divide_and_conquer / build_binary_tree_pr… (#1653)
* translation: Update chapter_divide_and_conquer / build_binary_tree_problem.md

* Update build_binary_tree_problem.md

preorder-> pre-order
inorder -> in-order

* Update build_binary_tree_problem.md

* Update build_binary_tree_problem.md

* Update build_binary_tree_problem.md

* Update build_binary_tree_problem.md

* Update build_binary_tree_problem.md

* Update build_binary_tree_problem.md
2025-03-09 06:32:30 +08:00
Phoenix Xie 2fcdd499ea
translation: Update chapter_sorting / bubble_sort.md (#1646)
* translation: Update chapter_sorting / bubble_sort.md

* Update bubble_sort.md

line 3 updated. 'reminiscent of' - > 'like'

* Update bubble_sort.md

* Update bubble_sort.md

* Update bubble_sort.md

* Update bubble_sort.md
2025-03-09 06:29:03 +08:00
Peng Chen 18a5fec836
translate merge_sort.md (#1645)
* translate merge_sort.md

* translate merge_sort.md

* sub-array, postorder --> subarray, post-order

* Fix the typo

* fix the typo

* Update merge_sort.md

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2025-03-09 06:28:27 +08:00
qinmu e3170c372a
translation: update counting_sort.md (#1638)
* doc: update translations

* doc: update translations

* doc: update translations

* doc: optimize translations

* doc: optimize translations
2025-03-09 06:27:04 +08:00
Peng Chen f5282698d5
Fix the comma (#1672) 2025-02-26 05:08:11 +08:00
AsaoOoo0o0o 98cd3a8076
fix: update the implementation of simple_hash.js and .ts (#1656) 2025-02-25 04:54:48 +08:00
Thomas 35c1885b3e
translation update: divide and conquer (#1659)
* translation update: divide and conquer

* resolve comments

* resolve further comments
2025-02-25 04:51:26 +08:00
Phoenix Xie 34b01c12d6
translation: Update chatper_backtracking / index.md (#1655)
* translation: Update chatper_backtracking / index.md

* Update index.md
2025-02-25 04:49:33 +08:00
Peng Chen 0114546a31
translation: Update chapter_sorting/quick_sort.md (#1637)
* translation: Update chapter_sorting/quick_sort.md

* Update quick_sort.md

* translate quick_sort.md

* sub-array --> subarray

* update quick_sort.md
2025-02-25 04:38:55 +08:00
SamJin98 16fbc4979f
translation: update insertion_sort.md (#1630)
* translation: update insertion_sort.md

* fix: revise insertion_sort.md translation

* fix: revert title name

* fix: updating `key` to `base`
2025-02-25 04:38:19 +08:00
Phoenix Xie 9dfd0217a3
translation: Update chapter_divide_and_conquer / summary.md (#1647)
* translation: Update chapter_divide_and_conquer / summary.md

* Update summary.md

* Update summary.md - line 8

line 8 'usually' -> 'typically'

* Update summary.md

line 9 was refined

* Update summary.md

line 10 'splitting' -> 'partitioning'
2025-02-15 21:24:29 +08:00
Thomas e19276a5f1
translation: update bucket sort translation (#1639)
* update bucket sort translation

* resolve comments
2025-02-15 21:16:58 +08:00
Yuelin Xin 3a309c88af
translation: optimize translation for selection sort (#1600)
* optimize translation for selection sort

* update selection sort translation
2025-02-15 21:14:17 +08:00
yanedie 4ff889c249
translation: Update binary_search_insertion.md and binary_search_edge.md (#1554)
* translation: Update binary_search_insertion.md

* fix: Clarify binary search insertion and multiple targets handling

* fix: Update binary search insertion title and nav link

* translation: update binary_search _edge.md

* Fix typos and clarify binary search edge cases

* fix: Revert binary search insertion title

* revert the chapter 10.2 title

* Update binary_search_insertion.md

* Update binary search insertion and binary search edge

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2025-02-14 22:14:59 +08:00
rongyi 00738f5bb4
idomatic rust (#1652)
* idomatic rust

* Update linkedlist queue/deque
2025-02-10 10:40:29 +08:00
Phoenix Xie eec69f45af
translation: chapter_sorting/index.md (#1644) 2025-02-10 10:38:24 +08:00
K3v123 95bd58b0d0
Translation: Update index.md (#1633)
Chapter 12 of "divide and conquer
2025-02-10 10:36:17 +08:00
K3v123 2725e5a9dc
Translation: Update radix_sort.md (#1632)
* Translation: Update radix_sort.md

* Translation Update radix_sort.md

fixed errors mentioned by yuelinxin
2025-02-10 10:35:52 +08:00
K3v123 387f93b56f
Translation: Update heap_sort.md (#1631)
* Translation: Update heap_sort.md

* Translation: Update heap_sort.md

updated per yuelinxin's suggestion.
2025-02-10 10:35:18 +08:00
K3v123 3d12f84a01
translation: Update summary.md (#1629)
* translation: Update summary.md

* translation: Update summary.md

re-edited the radix sort part. my main worry is the radix sort and bucket sort, Im just wondering if I actually refined it well or not

* Translation: Update summary.md

updated as per  yuelinxin's suggestions.
2025-02-10 10:34:20 +08:00
Spark 4c181c45c5
translation: Update heap.md (#1604)
* heap.md

* Update heap.md

* Update heap.md
2025-02-03 16:50:10 +08:00
Thomas 28e43b4446
translation: update heap index translation (#1620)
* update heap index translation

* revise based on comments

* further adjustment on words
2025-02-01 19:35:37 +08:00
Frost Wong e36453ac25
replace std::mem::replace with std::mem::take according to clippy sugguestion (#1611)
Co-authored-by: frost.wong <happyhackerwqc@foxmail.com>
2025-01-26 06:09:26 +08:00
Yudong Jin ac0da11157
Bug fixes and improvements (#1627)
* Update Copyright 2024 to 2025.

* Fix the flex of .profile-cell for mobile devices.

* Update performance_evaluation.md

* 抛出 -> 给出

* Sync zh and zh-hant version.

* Improve the landing page of the English version.

* Bug fixes

* Fix readme-typing-svg

* Update readme-typing-svg

* Bug fixes

* sync zh and zh-hant versions.
2025-01-21 20:00:58 +08:00
Sammy 5dc9dd879c
translation: Update chapter_computational_complexity/performance_evaluation.md (#1557)
* Update chapter_computational_complexity/performance_evaluation.md

* fixed translation based on the suggestions
2025-01-21 19:33:23 +08:00
KawaiiAsh 4db90555a7
Update binary_tree.md (#1618)
* Update binary_tree.md

* Update binary_tree.md

Thank you for the fix!

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2025-01-21 19:29:09 +08:00
RafaelCaso aa8a7f59d3
translation: update searching_algorithm_revisited.md (#1559)
* Update searching_algorithm_revisited.md

* Update searching_algorithm_revisited.md

fix typo in original commit
2025-01-21 19:19:58 +08:00
Peter Chen; Kohan Chen 18027ee26c
add notation of m and n in analysis of complexity (#1621)
* fix: notation of m and n in analysis of complexity

As title, complexity variable is not defined previously.

* Update dp_solution_pipeline.md

* Update dp_solution_pipeline.md

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2025-01-21 19:18:03 +08:00
llql1211 98daefa67a
Update heap_sort.md (#1626) 2025-01-21 18:51:12 +08:00
Rui 1a8b4f6364
Update linkedlist_deque.py (#1625)
According to PEP 8, "Comparisons to singletons like None should always be done with is or is not, never the equality operators."
2025-01-21 18:46:41 +08:00
qinmu 9c78c513c2
translation: ram and cache (#1591)
* doc: en translation for ram and cache

* doc: update currency from yuan to dollars

* doc: update EOF character

* doc: remove the redundant EOS character

* doc: remove redundant space character and polish several translations

* doc: polish translations

* doc: remove unnecessary 'the' and update translations

* Update ram_and_cache.md

* Update ram_and_cache.md

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2025-01-14 03:19:12 +08:00
linyejoe2 828405d234
'丟擲' is not common for zh-hant in this place, '說' or like zh useing '拋出' will be a better translation. (#1607) 2025-01-14 03:09:40 +08:00
Yuelin Xin a2cec10e7f
translation: optimized translation of sorting/sorting_algorithm.md (#1590)
* optimize sorting_algo

* update terminology
2025-01-14 03:04:51 +08:00
rongyi 7503a33e8c
fix rust linked list (#1609) 2025-01-14 02:58:17 +08:00
Yudong Jin 2a955f937c
Bug fixes and improvements (#1602)
* Fix the search panel on mobile devices.

* Fix the search panel for mobile devices.

* Update about_the_book.md
2025-01-02 21:50:42 +08:00
趙子賢 636b0738fa
fix(hash_collision): typo of zh-Hant translation in "線性探查" section (#1599)
* Fix typo of zh-Hant translation in "線性探查" section

* Fix the same typo in hash summary Q&A section

* Update hash_collision.md

* Update summary.md

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2024-12-31 19:20:44 +08:00
steventimes a36b301464
translation: Update chap_tree/summary.md (#1555)
* Update summary.md

* Update summary.md

* change_2_pull_request
2024-12-31 19:15:04 +08:00
Flamingo 292b107af2
fix(bubble-sort): update incorrect variable name in test output (#1595) 2024-12-20 17:15:22 +08:00
Thomas 4db5c19011
translation: graph summary updates (#1587)
* translation: graph summary updates

* resolve grammar issues
2024-12-12 20:11:28 +08:00
Yudong Jin 356cc35e8a
Update the links to the zh-hant version of the PDF. (#1588) 2024-12-07 23:01:46 +08:00
Yudong Jin dad0a3fd95
Prepare 1.2.0 release (#1585)
* Sync zh and zh-hant versions

* Update the list of contributors.

* Update time_complexity_simple_example.png

* Reduce size of the RGBA images for zh-hant version.

* Sync the zh-hant version of terminology.md

* Prepare 1.2.0 release

* Update the contributors list.
2024-12-06 09:03:43 +08:00
pzpz e41b0a3156
Fix the function for printing the queue (#1573)
* renfined!

* Add toArray() function to array_queue.c and array_deque.c

---------

Co-authored-by: Xi-Row <astruggle123@putlook.com>
Co-authored-by: krahets <krahets@163.com>
2024-12-04 19:38:30 +08:00
K3v123 b6939da46c
translation: Update replace_linear_by_hashing.md (#1551)
* translation: Update replace_linear_by_hashing.md

refined some parts of it.

* Update replace_linear_by_hashing.md

* Update replace_linear_by_hashing.md

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2024-12-04 18:05:03 +08:00
Yudong Jin abf1f115bf
Bug fixes and improvements (#1581)
* A bug fixes

* Sync zh and zh-hant versions.

* Fix a question in chapter_array_and_linkedlist/summary.md

* Optimize a definition in what_is_dsa.md

* Fix the Contributing guidelines for Chinese-to-English.

* Add a q&a in chapter_array_and_linkedlist/summary.md

* Sync zh and zh-hant versions.

* Update .gitignore

* Sync zh and zh-hant versions.
2024-12-04 17:58:28 +08:00
Thomas 6348dbe18d
translation: binary search updates (#1569)
* translation: binary search updates

* fix minor gramma and expression issues
2024-12-04 17:48:48 +08:00
YuZou ca774eefbf
Update time_complexity.md (#1578)
* Bug fixes and improvements (#1577)
 * correct the implement of exp_recur function and remove +1 operation from the function to simulate the cell division process

* Update time_complexity.rs

* Update time_complexity.md

---------

Co-authored-by: zouy26 <zouy26@chinaunicom.cn>
Co-authored-by: Yudong Jin <krahets@163.com>
2024-12-04 17:36:11 +08:00
Yudong Jin 2a9db6d039
Bug fixes and improvements (#1572)
* Sync zh and zh-hant versions.

* Remove the polyfill.io link from mkdocs.yml

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

* Fix graph.md

* Update avatars for English version reviewers.

* Sync zh and zh-hant versions.

* Fix two_sum_brute_force.png

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

* Format index.html
2024-11-25 19:21:11 +08:00
Anurag Pandey 01a5f7b09f
Improved HTML Structure for Better Accessibility and Maintainability (#1434)
* Improved HTML Structure for Better Accessibility and Maintainability

Commit Description:

    Semantic Sectioning and Class Names:
        Updated class names to be more descriptive.
        Ensured better readability and maintainability.

    Alt Text for Images:
        Added alt attributes to all <img> tags to improve accessibility.

    SVG Elements:
        Added appropriate role attributes to SVG elements.

    External Links:
        Updated external links to open in a new tab using target="_blank".
        Added rel="noopener noreferrer" for security reasons.

    CSS Separation:
        Inlined styles for demonstration purposes but recommended moving them to a separate stylesheet for better separation of concerns.

* Update index.html

* Update index.html

* Update index.html

* Update index.html

* Update index.html

* Update index.html

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2024-11-25 19:15:06 +08:00
sslmj2020 894e3d536b
Update array_binary_tree.cpp (#1568)
打印的小错误
2024-11-24 00:39:33 +08:00
Yudong Jin 14608d4e92
Update CONTRIBUTING.md (#1565) 2024-11-20 20:38:48 +08:00
Yudong Jin 954169d618
Update CONTRIBUTING.md (#1564) 2024-11-20 19:45:03 +08:00
qinmu 05e0e1d244
translation: chapter_tree/binary_tree.md (#1502)
* doc: translate chapter_tree/binary_tree.md to English

* Update binary_tree.md

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2024-11-17 20:49:36 +08:00
K3v123 fb04ff6535
translation update: Update summary.md (#1549)
* translation update: Update summary.md

added and refined some parts.
I feel like that this chapter is already pretty well translated.

* translation: Update summary.md

rewritten some parts of the sentence as per Thomas suggested.
please note that some parts I re-wrote it a bit differently.

* translation update: summary.md

Added what Ymmma suggested
2024-11-17 20:49:26 +08:00
K3v123 9a2c1355ec
translation: Update index.md (#1548)
* translation: Update index.md

refined some parts of the sentences.

changed 'in' to 'on' as it conveys a sense of movement along a path

* translation: Update index.md

changed some words per Thomas's suggestions.
2024-11-17 20:47:41 +08:00
Fleey 6a74972080
fix(lang: c, chapters: searching, sorting): Some serious errors (#1531)
* fix: correct hash table insertion

* Use a pointer to a pointer instead of a single pointer in the insert function, ensuring proper updates to the hash table
* Bug fixes: This fixes issues with empty results.

* fix: correct issues in radix sort

* Replaced loop-based array copy with memcpy to ensure efficient memory copying in countingSortDigit
* Fixed a bug in radixSort where the maximum value search loop skipped the last element
* Bug fix: Ensures all elements are checked when determining the maximum value in the array

* perf: improve memory management by adding explicit memory release

* revert: Revert to using the old loop override array method and drop specific api's like memcpy.
2024-11-10 02:00:53 +08:00
Yudong Jin 73eab4c0ec
Update reviewer profiles (#1547)
* Sync zh and zh-hant versions.

* Remove the polyfill.io link from mkdocs.yml

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

* Fix graph.md

* Update avatars for English version reviewers.

* Sync zh and zh-hant versions.
2024-11-07 20:56:16 +08:00
Flamingo 57cf6b1ea6
fix some typos (#1540) 2024-10-31 21:26:28 +08:00
hpstory b3b10f2300
fix(csharp): priority queue comparer initialization (#1542) 2024-10-31 21:25:32 +08:00
rongyi 68a61f23d5
make dfs same as c/c++ and other small improvement (#1543) 2024-10-31 21:24:56 +08:00
qinmu 7d708b4fce
doc: translate chapter_tree/index.md to English (#1501)
* doc: translate chapter_tree/index.md to English

* doc: update translations
2024-10-29 17:25:46 +08:00
rongyi ef3010bd77
idomatic structure rust code, no include macro (#1528) 2024-10-23 18:49:47 +08:00
Akshit 0c60037e56
Update avl_tree.md (#1524)
Syntax for avl trees updated
2024-10-10 18:23:54 +08:00
Yudong Jin 5849ae4ada
Sync zh and zh-hant versions. (#1523) 2024-09-28 09:28:44 +08:00
ZhongGuanbin dedb4aaced
Update linked_list.md (#1521)
双向链表的Dart代码可能存在语法错误,因为前驱节点和后继节点可能为空,所以需要添加问号,否则无法通过空安全检查
2024-09-28 09:13:18 +08:00
Spark 40d13cb81f
doc: translate chapter_tree/binary_tree_traversal.md (#1510)
* Update binary_tree_traversal.md

* Update binary_tree_traversal.md with review
2024-09-24 18:00:36 +08:00
bongbongbakudan c12d01a752
Update my_list.js (#1511)
修改insert注释
2024-09-24 17:57:34 +08:00
steventimes 2737357242
translation: refine translation of binary_search_tree.md (#1484)
* translation_refine_bst

Signed-off-by: steventimes <stevenyang0316@gmail.com>

* Update binary_search_tree.md

* Update binary_search_tree.md

---------

Signed-off-by: steventimes <stevenyang0316@gmail.com>
Co-authored-by: Yudong Jin <krahets@163.com>
2024-09-12 17:46:08 +08:00
Enlightenus e0d617edbb
translation: refine translation of hash_map.md (#1483)
* Update hash_map.md

* Update hash_map.md

* Update hash_map.md to improve concise
2024-09-12 17:39:54 +08:00
rongyi 7a345fc66b
Idiomatic rust (#1505) 2024-09-12 17:38:16 +08:00
Yuelin Xin 1cc310a682
refine graph_traversal.md (#1400) 2024-09-02 14:09:27 +08:00
Yuelin Xin eecf6bac3f
refine graph_operations.md (#1399) 2024-09-02 14:08:59 +08:00
Risun 2cd2a94ce6
fix(backtracking): minor mistake in Rust code for subset_sum_ii (#1487)
* fix(backtracking): minor mistake in Rust code for subset_sum_ii

* Update subset_sum_ii.rs

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2024-08-26 10:12:47 +08:00
rongyi 8a6ce26f6a
idiomatic rust (#1485)
* idomatic rust

* More idiomatic rust

* make rust code more idiomatic

* update
2024-08-23 02:33:47 +08:00
ZhongYuuu 6b2c38cae4
[cpp] Stick with swap (#1474)
* [cpp] Stick with swap

* [cpp] Stick with swap
2024-08-06 15:08:01 +08:00
Seven Du f4baa7d9de
add a period at the end (#1478) 2024-08-06 15:05:30 +08:00
Seven Du fc7efa28a7
remove extra space (#1477)
* remove extra space

* Update max_capacity_problem.md

* Update algorithms_are_everywhere.md

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2024-08-06 15:04:53 +08:00
溯渺 0bff488383
Update binary_tree.md (#1454)
* Update binary_tree.md

关于完全二叉树严谨性补充:完美二叉树是一棵特殊的完全二叉树,完全二叉树的最底层节点可以是满的。

* Update binary_tree.md

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2024-08-01 17:32:49 +08:00
Enlightenus f0755bdfa6
translation: Refine the first paragraph of Time Complexity (#1471)
* Update time_complexity.md

Update first paragraph to avoid confusion between time complexity and run time

* Update time_complexity.md

Refine the first paragraph to keep the definition of time complexity

* Update time_complexity.md

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2024-08-01 15:58:39 +08:00
Yudong Jin c9041c5c5e
Bug fixes and improvements (#1472)
* preorder, inorder, postorder -> pre-order, in-order, post-order

* Bug fixes

* Bug fixes

* Update what_is_dsa.md

* Sync zh and zh-hant versions

* Sync zh and zh-hant versions.

* Update performance_evaluation.md and time_complexity.md

* Add @khoaxuantu to the landing page.

* Sync zh and zh-hant versions

* Add @ khoaxuantu to the landing page of zh-hant and en versions.

* Sync zh and zh-hant versions.

* Small improvements

* @issue :  #1450 (#1453)

Fix writing "obsecure" to "obscure"

Co-authored-by: Gaya <kheliligaya@gmail.com>

* Update the definition of "adaptive sorting".

* Update n_queens_problem.md

* Sync zh, zh-hant, and en versions.

---------

Co-authored-by: Gaya-Khelili <50716339+Gaya-Khelili@users.noreply.github.com>
Co-authored-by: Gaya <kheliligaya@gmail.com>
2024-07-30 16:56:59 +08:00
Yuelin Xin 89a911583d
translation: refine translation of chapter_heap/summary.md (#1383)
* refine translation of heap/summary.md

* Update summary.md

* Update summary.md
2024-07-26 16:50:22 +08:00
Estevão Goerll b884d385e3
fix: right-left and left-right inversion for the English version of AVL Tree (#1448)
* Fix right-left and left-right inversion on AVL Binary Tree

* Update avl_tree.md

* Update avl_tree.md

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2024-07-26 16:48:35 +08:00
Rui 2758e06374
remove unnecessary type conversions (#1411) 2024-07-14 18:36:00 +08:00
Yuelin Xin ff6d42bd9b
translation: refine translation of chapter_graph/graph.md (#1385)
* refine translation of graph/graph.md

* Update graph.md
2024-07-12 18:20:01 +08:00
Flamingo f4a6d2127c
fix: correct comment translation in binary_tree.md (#1406) 2024-07-01 15:10:46 +08:00
Rui 27d59f65a6
fix invalid code comment (#1405)
* Remove invalid comment

* Update time_complexity.md

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2024-06-28 19:20:41 +08:00
Flamingo 4190eca41a
fix(Go): code comment error (#1404)
* fix: comment error

* fix: comment error in zn-hant version
2024-06-28 19:18:17 +08:00
Yuelin Xin a7c241609f
translation: refine translation of chapter_graph/index.md (#1384)
* refine translation of graph/index.md

* Update index.md
2024-06-19 15:45:29 +08:00
qinmu 9f0bec5f50
translation: optimize the translation of hash_map.md (#1358)
* feat: translate hash_map.md to English

* doc: remove redundant lines and polish words

* chore: remove redundant line

* doc: update hash_map translation

* doc: refine expressions
2024-06-13 15:31:15 +08:00
Deming Chu 427c7ac59d
translation: refine the translation of data_structure/summary (#1374)
* feat: translate data_structure/summary to English

* fix space issue

* replace the encoding naming (krahets comment)

* refine (K3v123 comment)
2024-06-13 15:20:29 +08:00
rongyi 017b95f003
Make rust more idomatic (#1386) 2024-06-13 15:19:21 +08:00
nil 0774920d7f
fix(Go): Update array_queue.go and array_deque.go (#1362)
* 🐞 fix: 队列为空时不应该操作指向

* 🧪 test: 添加pop测试用例

* 🔧 build: 修改testify依赖包

* 🐞 fix: 双向队列为空时,pop不操作指向

* 🔧 build:

Remove third-party packages

* Delete codes/go/go.sum

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2024-05-31 17:38:27 +08:00
Yudong Jin 3f4220de81
Bug fixes and improvements (#1380)
* preorder, inorder, postorder -> pre-order, in-order, post-order

* Bug fixes

* Bug fixes

* Update what_is_dsa.md

* Sync zh and zh-hant versions

* Sync zh and zh-hant versions.

* Update performance_evaluation.md and time_complexity.md

* Add @khoaxuantu to the landing page.

* Sync zh and zh-hant versions

* Add @ khoaxuantu to the landing page of zh-hant and en versions.
2024-05-31 16:39:06 +08:00
Yudong Jin 39a6890b7e
Add intial translation of the figures for the chapters of backtracking, divide and conquer, appendix (#1337)
* Add intial translation of the figures for the chapters of backtracking, divide and conquer, appendix

* Update
2024-05-31 16:01:23 +08:00
Yudong Jin 59839c2437
Add intial translation of the figures for the chapters of graph, searching, and sorting (#1338)
* Add intial translation of the figures for the chapters of graph, searching, and sorting

* Update
2024-05-31 16:00:43 +08:00
Yudong Jin 8b3e705c71
Add intial translation of the figures for the chapters of hashing, tree, and heap (#1339)
* Add intial translation of the figures for the chapters of hashing, tree, and graph

* Update
2024-05-31 15:59:59 +08:00
Yudong Jin ae2ff7a68a
Add intial translation of the figures for the chapters of dynamic programming, greedy (#1336)
* Add intial translation of the figures for the chapters of dynamic programming, greedy

* Update
2024-05-31 15:58:43 +08:00
khoaxuantu a704c0d7f2
feat: finalize ruby code transpilation (#1379) 2024-05-31 12:30:55 +08:00
khoaxuantu a14be17b74
[feat] add ruby code - chapter dynamic programming (#1378) 2024-05-30 17:11:56 +08:00
rongyi 63bcdb798a
[Rust] make rust part more idomatic and fix panic of backtrack template (#1370)
* Drop unused variable

* Idiomatic rust

* Fix panic template
2024-05-24 16:21:17 +08:00
khoaxuantu aa818945f0
feat: Add Ruby code - chapter "Backtracking" (#1373)
* [feat] add ruby code - chapter backtracking

* feat: add ruby code block - chapter backtracking
2024-05-24 15:41:40 +08:00
rongyi 21be3fdaf8
[Rust] Normalize mid calculation in case overflow (#1363)
* Normalize mid calculate in case overflow

* Change ALL language

* Update merge_sort.py

* Update merge_sort.zig

* Update binary_search_tree.zig

* Update binary_search_recur.py

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2024-05-18 18:19:19 +08:00
Lanjing Gong 0e221540a3
fix(c): Fix malloc allocation of secondary pointers can lead to dump issues (#1367) 2024-05-18 18:17:33 +08:00
CarrotDLaw 9afbc9eda5
[Rust] Use arrays instead of vectors in Chapter 4.1 Array (#1357)
* [Rust] Use array in chapter 4.1

* docs: update comments

* docs: update comments

* docs: update comments

* fix: update slices

* docs: update comments
2024-05-15 18:31:48 +08:00
rongyi 840692acce
Idiomatic rust (#1364) 2024-05-15 18:16:55 +08:00
khoaxuantu 9e569cf520
feat: add ruby code - chapter "divide and conquer" (#1361) 2024-05-15 18:14:15 +08:00
rongyi 063a41fa7f
[Rust] No need to use mut iter (#1356)
* No need to use mut iter

* Update iter
2024-05-12 14:49:25 +08:00
rongyi ebff1cce9f
Stick with swap (#1352) 2024-05-11 17:59:44 +08:00
rongyi 7a96f6a743
Fix panic when array's len is less than 2 (#1353) 2024-05-11 17:59:11 +08:00
khoaxuantu 1f606d6852
feat: add ruby codes - chapter greedy (#1350) 2024-05-08 18:38:35 +08:00
rongyi 56a165bf98
cargo fmt code (#1349) 2024-05-08 18:37:38 +08:00
Yudong Jin c4a7966882
Bug fixes and improvements (#1348)
* Add "reference" for EN version. Bug fixes.

* Unify the figure reference as "the figure below" and "the figure above".
Bug fixes.

* Format the EN markdown files.

* Replace "" with <u></u> for EN version and bug fixes

* Fix biary_tree_dfs.png

* Fix biary_tree_dfs.png

* Fix zh-hant/biary_tree_dfs.png

* Fix heap_sort_step1.png

* Sync zh and zh-hant versions.

* Bug fixes

* Fix EN figures

* Bug fixes

* Fix the figure labels for EN version
2024-05-06 14:44:48 +08:00
Yudong Jin 8e60d12151
Add the initial EN translation for C++ code (#1346) 2024-05-06 13:31:46 +08:00
popozhu 9e4017b3fb
Update heap.md (#1344) 2024-05-06 05:32:23 +08:00
Yudong Jin 1c0f350ad6
translation: Add Python and Java code for EN version (#1345)
* Add the intial translation of code of all the languages

* test

* revert

* Remove

* Add Python and Java code for EN version
2024-05-06 05:21:51 +08:00
Yudong Jin b5e198db7d
Add intial translation of the figures for the rest of the chapters (#1340) 2024-05-04 19:24:41 +08:00
Yudong Jin 0047934042
Update the EN figures for the chapter of preface, introduction, complexity analysis, data structure, array and linked list, stack and queue (#1335) 2024-05-04 18:58:20 +08:00
K3v123 cac10b07a1
Translation: Update binary_tree.md (#1287)
* Translation: Update binary_tree.md

simplified some parts while others added a few words to make it clearer

* translation: Update binary_tree.md

edited most of the stuff that QiLOL has suggestion, again thanks QiLOL for the review

* translation: Update binary_tree.md

changed to simpler words instead.
Did not update the 2nd part, as I'm waiting for Khrahets to make the final decision
2024-05-03 19:50:36 +08:00
cyyy aebaa3ef02
translation: Update hash_collision.md (#1153)
* 1

* Move `docs-en` to `en/docs`

* Revert the moving operation

* 1

* Update hash_collision.md

---------

Co-authored-by: krahets <krahets@163.com>
2024-05-03 19:50:20 +08:00
khoaxuantu cb32c525e7
feat: Add Ruby code - chapter "Sorting" (#1333)
* feat: add ruby code - chapter sorting

* Update radix_sort.rb

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2024-05-03 19:46:42 +08:00
Hongting Su a6be0ffdc3
Update graph_traversal.md (#1334)
The implementation uses hash set to store all visited vertices instead of hash table. Change the description text from "hash table" to "hash set"
2024-05-03 19:41:50 +08:00
huangjikun ee67d3e6a7
Maintain the same semantics as other languages in n_queens.go (#1329) 2024-05-03 19:40:59 +08:00
Yudong Jin d2d49551e3
Bug fixes for the figures of zh-hant version. (#1327)
Reduce image file size by ~10%.
2024-05-01 17:59:23 +08:00
Yudong Jin 354b81cb6c
Add "reference" for EN version. Bug fixes. (#1326) 2024-05-01 06:49:33 +08:00
Yudong Jin bb511e50e6
Add the initial translation of chapter "greedy" (#1320) 2024-05-01 05:57:39 +08:00
Yudong Jin 316b0e9215
Add the initial translation of chapter "appendix" (#1325) 2024-05-01 05:57:29 +08:00
Yudong Jin baf30b1c92
Add the initial translation of chapter "dynamic programming" (#1319) 2024-05-01 05:57:15 +08:00
Yudong Jin 3eb929ca6d
Add the initial translation of chapter "backtracking" (#1323) 2024-05-01 05:57:01 +08:00
Yudong Jin 3bd416600e
translation: Add the initial translation of chapter "divide and conquer" (#1322)
* Add the initial translation of chapter "divide and conquer"

* Update index.md

* Update summary.md

* Update index.md

* Update summary.md
2024-05-01 05:56:54 +08:00
Yudong Jin 01a2e31203
Add the initial translation of chapter "sorting" (#1321) 2024-05-01 05:56:35 +08:00
Yudong Jin 96597b8aaa
Add the initial translation of chapter "searching" (#1324) 2024-05-01 05:56:27 +08:00
Martin Xu 59d07264fc
feat: add ruby code block - bucket sort (#1285)
* feat: add ruby code block - bucket sort

* Update codes/ruby/chapter_sorting/bucket_sort.rb

Co-authored-by: khoaxuantu <68913255+khoaxuantu@users.noreply.github.com>

* Update codes/ruby/chapter_sorting/bucket_sort.rb

Co-authored-by: khoaxuantu <68913255+khoaxuantu@users.noreply.github.com>

* Update bucket_sort.rb

---------

Co-authored-by: khoaxuantu <68913255+khoaxuantu@users.noreply.github.com>
Co-authored-by: Yudong Jin <krahets@163.com>
2024-04-30 16:00:39 +08:00
nuomi1 84bb11522e
feat: remove setup-swift (#1312)
* feat: remove setup-swift

* Test failure

* Test success

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2024-04-30 15:59:56 +08:00
洪鈞閔 ( jasper ) 68f3a453e1
feat: add ruby code block - merge sort (#1260)
* feat(codes/ruby/chapter_sorting/merge_sort.rb): add merge_sort ruby file

* feat(codes/ruby/chapter_sorting/merge_sort.rb): modify comment space

* feat(codes/ruby/chapter_sorting/merge_sort.rb): set array default value

Co-authored-by: khoaxuantu <68913255+khoaxuantu@users.noreply.github.com>

* feat(codes/ruby/chapter_sorting/merge_sort.rb): driver code add if logic

Co-authored-by: khoaxuantu <68913255+khoaxuantu@users.noreply.github.com>

* feat(codes/ruby/chapter_sorting/merge_sort.rb): modify comment style

Co-authored-by: khoaxuantu <68913255+khoaxuantu@users.noreply.github.com>

* feat(codes/ruby/chapter_sorting/merge_sort.rb): modify logic instruction

Co-authored-by: khoaxuantu <68913255+khoaxuantu@users.noreply.github.com>

---------

Co-authored-by: khoaxuantu <68913255+khoaxuantu@users.noreply.github.com>
2024-04-30 15:58:47 +08:00
洪鈞閔 ( jasper ) 3f857db457
feat: add ruby code block - heap sort (#1261)
* feat(codes/ruby/chapter_sorting/heap_sort.rb): add heap_sort ruby file

* feat(codes/ruby/chapter_sorting/heap_sort.rb): modify comment space

* feat(codes/ruby/chapter_sorting/heap_sort.rb): modify code space style

* feat(codes/ruby/chapter_sorting/heap_sort.rb): modify logic instruction

Co-authored-by: khoaxuantu <68913255+khoaxuantu@users.noreply.github.com>

* feat(codes/ruby/chapter_sorting/heap_sort.rb): driver code add if logic

Co-authored-by: khoaxuantu <68913255+khoaxuantu@users.noreply.github.com>

---------

Co-authored-by: khoaxuantu <68913255+khoaxuantu@users.noreply.github.com>
2024-04-30 15:58:37 +08:00
Yudong Jin 870e3e5cb2
Bug fixes and improvements (#1318)
* Sync zh and zh-hant versions

* Update en/README.md

* Add a Q&A for chapter of introduction

* Update the callout headers

* Sync zh ang zh-hant versions

* Bug fixes
2024-04-30 15:52:05 +08:00
huangjikun 84b1ce2497
Fix incorrect method name in permutations_ii.go (#1313) 2024-04-30 14:13:01 +08:00
bluebean-cloud a3950e1def
feat: Add ruby codes - chapter "Heap" (#1300)
* init heap Ruby

* feature: finish chapter heap for ruby

* fix delete heap.rb

* fix: Fix code style

* Update codes/ruby/chapter_heap/my_heap.rb

Co-authored-by: khoaxuantu <68913255+khoaxuantu@users.noreply.github.com>

* Update codes/ruby/chapter_heap/top_k.rb

Co-authored-by: khoaxuantu <68913255+khoaxuantu@users.noreply.github.com>

* fix: apply the suggested changes

* fix to_a

* Update my_heap.rb

---------

Co-authored-by: khoaxuantu <68913255+khoaxuantu@users.noreply.github.com>
Co-authored-by: Yudong Jin <krahets@163.com>
2024-04-28 22:24:51 +08:00
nuomi1 ca55e818a5
feat: update os and swift (#1311) 2024-04-28 22:22:03 +08:00
smilelsb 75873f0a05
fix(typo): Update linked_list.md (#1307)
它表现出先进后出的特性,对应栈;它表现出先进先出的特性,对应队列。
适当修改为“它表现的特性为先进后出”和“它表现的特性为先进先出”。
因为原本的语句第一次阅读出现“出先进后”的错误断句
2024-04-28 22:02:39 +08:00
Yudong Jin cfc273783b
feat: Add glossary and description for "哈希集合" (#1310) 2024-04-28 22:00:25 +08:00
rongyi a88c7b9862
Change remove to pop (#1309) 2024-04-28 20:47:03 +08:00
CharlesHsu 71b7cc8ef6
Enhance accessibility of MathJax script loading with `cdnjs` (#1304)
* Add fallback mechanism for MathJax script loading to enhance global accessibility.

* Update mkdocs.yml

* Update mathjax.js

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2024-04-26 19:13:05 +08:00
khoaxuantu 9e7fbf249f
feat: add ruby code - chapter graph (#1303) 2024-04-26 17:30:55 +08:00
K3v123 69cb171dd8
Translation: Update index.md (#1286)
* Translation: Update index.md

simplified the words using "vibrant" instead. used illustrate instead of demonstrate because I'm thinking the image "illustrates" the concept.

* Translation: Update index.md

Changed to what  yuelinxin has suggested. thanks for the suggestion.
2024-04-23 21:23:16 +08:00
Shyam Chen 1a99dd420f
feat(JavaScript): Add the workflow file for CI check (#1296)
* feat(JavaScript): Add the workflow file for CI check

* Apply suggestions from code review
Co-authored-by: krahets <krahets@163.com>

* Test failure

* Update javascript.yml

* Test success

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2024-04-22 17:51:44 +08:00
krahets a7f4340e55 Update README 2024-04-22 17:14:14 +08:00
huangjikun 54ced94e4f
Fix incorrect indexes in two_sum.go (#1297) 2024-04-22 02:28:54 +08:00
Yudong Jin f616dac7da
Bug fixes and improvements (#1298)
* Fix is_empty() implementation in the stack and queue chapter

* Update en/CONTRIBUTING.md

* Remove "剩余" from the state definition of knapsack problem

* Sync zh and zh-hant versions

* Update the stylesheets of code tabs

* Fix quick_sort.rb

* Fix TS code

* Update chapter_paperbook

* Upload the manuscript of 0.1 section

* Fix binary_tree_dfs.rb

* Bug fixes

* Update README

* Update README

* Update README

* Update README.md

* Update README

* Sync zh and zh-hant versions

* Bug fixes
2024-04-22 02:26:32 +08:00
khoaxuantu 74f1a63e8c
feat: add ruby code blocks - chapter tree (#1293) 2024-04-19 23:42:20 +08:00
Shyam Chen 587344da62
feat(TypeScript): Add the workflow file for CI check (#1280)
* feat(TypeScript): Add the workflow file for CI check

* fix: Install TypeScript Execute (tsx)

* test: Test failed

* test: Test successful

* test: on windows

* Add a bug

* feat: type checking

* test: Test successful

* feat: add main

* fix: use process

* feat: use es-main

* Test failure

* feat: streamlined configuration

* Apply suggestions from code review
Co-authored-by: Yudong Jin <krahets@163.com>

* feat: remove lock file

* Test failure

* Test success

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2024-04-19 18:48:58 +08:00
cy-by-side 499419e4ce
Create quick_sort.rb (#1223)
* Create quick_sort.rb

* Update quick_sort.rb

* Update quick_sort.rb

* Update quick_sort.rb
2024-04-19 18:26:54 +08:00
khoaxuantu 19488b13c4
feat: add ruby codes - chapter tree (#1288) 2024-04-19 15:50:43 +08:00
Shyam Chen a587b01c4d
feat(appendix): TypeScript installation (#1279)
* feat(appendix): TypeScript installation

* Update installation.md

* Update installation.md

* Update installation.md

* Update installation.md

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2024-04-18 01:22:30 +08:00
K3v123 411a4b8a46
translation: Update chapter_graph/index.md (#1266)
* Translation: Update index.md

Just changed the words a little. honestly the Machine translation is good already.

* Translation: Update index.md

changed every to each.

* Translation: Update index.md

changed back to vast.
2024-04-15 18:45:07 +08:00
khoaxuantu be9931c8a1
feat: Add Ruby code - chapter "Hashing" (#1276)
* feat: add ruby code - chapter hashing

* feat: add ruby code blocks - chapter hashing

* fix: comments
2024-04-15 16:20:26 +08:00
nuquist19 2b11639103
fix(C): Update common.h (#1278)
请问这里为了防止重复包含头文件是不是应该改成COMMON_H,因为头文件名字叫做common.h
2024-04-15 14:54:28 +08:00
1956 changed files with 34091 additions and 2479 deletions

27
.github/workflows/javascript.yml vendored Normal file
View File

@ -0,0 +1,27 @@
name: JavaScript
on:
push:
branches: ['main']
paths: ['codes/javascript/**/*.js']
pull_request:
branches: ['main']
paths: ['codes/javascript/**/*.js']
workflow_dispatch:
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20.x
- uses: denoland/setup-deno@v1
with:
deno-version: v1.x
- name: Run JavaScript Code
run: deno run -A codes/javascript/test_all.js

View File

@ -14,16 +14,12 @@ on:
jobs:
build:
name: Swift ${{ matrix.swift }} on ${{ matrix.os }}
name: Swift on ${{ matrix.os }}
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-latest]
swift: ["5.10", "5.9", "5.8"]
os: ["ubuntu-22.04", "macos-14"]
steps:
- uses: swift-actions/setup-swift@v2
with:
swift-version: ${{ matrix.swift }}
- uses: actions/checkout@v4
- name: Build
run: swift build --package-path codes/swift

26
.github/workflows/typescript.yml vendored Normal file
View File

@ -0,0 +1,26 @@
name: TypeScript
on:
push:
branches: ['main']
paths: ['codes/typescript/**/*.ts']
pull_request:
branches: ['main']
paths: ['codes/typescript/**/*.ts']
workflow_dispatch:
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20.x
- name: Install dependencies
run: cd codes/typescript && npm install
- name: Check TypeScript code
run: cd codes/typescript && npm run check

5
.gitignore vendored
View File

@ -1,7 +1,7 @@
# macOS
.DS_Store
# Editor
# editors
.vscode/
**/.idea
@ -12,6 +12,3 @@
/build
/site
/utils
# test script
test.sh

View File

@ -17,24 +17,24 @@
</p>
<p align="center">
<img src="https://www.hello-algo.com/index.assets/animation.gif" width="389">
<img src="https://www.hello-algo.com/index.assets/running_code.gif" width="389">
<img src="https://www.hello-algo.com/index.assets/animation.gif" width="395">
<img src="https://www.hello-algo.com/index.assets/running_code.gif" width="395">
</p>
<p align="center">
<img src="https://img.shields.io/badge/Python-snow?logo=python&logoColor=3776AB">
<img src="https://img.shields.io/badge/C%2B%2B-snow?logo=c%2B%2B&logoColor=00599C">
<img src="https://img.shields.io/badge/Java-snow?logo=coffeescript&logoColor=FC4C02">
<img src="https://img.shields.io/badge/C%23-snow?logo=csharp&logoColor=512BD4">
<img src="https://img.shields.io/badge/Go-snow?logo=go&logoColor=00ADD8">
<img src="https://img.shields.io/badge/Swift-snow?logo=swift&logoColor=F05138">
<img src="https://img.shields.io/badge/JavaScript-snow?logo=javascript&logoColor=E9CE30">
<img src="https://img.shields.io/badge/TypeScript-snow?logo=typescript&logoColor=3178C6">
<img src="https://img.shields.io/badge/Dart-snow?logo=dart&logoColor=0175C2">
<img src="https://img.shields.io/badge/Rust-snow?logo=rust&logoColor=000000">
<img src="https://img.shields.io/badge/C-snow?logo=c&logoColor=A8B9CC">
<img src="https://img.shields.io/badge/Kotlin-snow?logo=kotlin&logoColor=7F52FF">
<img src="https://img.shields.io/badge/Zig-snow?logo=zig&logoColor=F7A41D">
<img src="https://img.shields.io/badge/Python-snow?logo=python&logoColor=3776AB" alt="" />
<img src="https://img.shields.io/badge/Java-snow?logo=coffeescript&logoColor=FC4C02" alt="" />
<img src="https://img.shields.io/badge/C%2B%2B-snow?logo=c%2B%2B&logoColor=00599C" alt="" />
<img src="https://img.shields.io/badge/C-snow?logo=c&logoColor=A8B9CC" alt="" />
<img src="https://img.shields.io/badge/C%23-snow?logo=csharp&logoColor=512BD4" alt="" />
<img src="https://img.shields.io/badge/JavaScript-snow?logo=javascript&logoColor=E9CE30" alt="" />
<img src="https://img.shields.io/badge/Go-snow?logo=go&logoColor=00ADD8" alt="" />
<img src="https://img.shields.io/badge/Swift-snow?logo=swift&logoColor=F05138" alt="" />
<img src="https://img.shields.io/badge/Rust-snow?logo=rust&logoColor=000000" alt="" />
<img src="https://img.shields.io/badge/Ruby-snow?logo=ruby&logoColor=CC342D" alt="" />
<img src="https://img.shields.io/badge/Kotlin-snow?logo=kotlin&logoColor=7F52FF" alt="" />
<img src="https://img.shields.io/badge/TypeScript-snow?logo=typescript&logoColor=3178C6" alt="" />
<img src="https://img.shields.io/badge/Dart-snow?logo=dart&logoColor=0175C2" alt="" />
</p>
<p align="center">
@ -51,7 +51,7 @@
- 全书采用动画图解,内容清晰易懂、学习曲线平滑,引导初学者探索数据结构与算法的知识地图。
- 源代码可一键运行,帮助读者在练习中提升编程技能,了解算法工作原理和数据结构底层实现。
- 鼓励读者互助学习,提问与评论通常可在两日内得到回复
- 提倡读者互助学习,欢迎大家在评论区提出问题与分享见解,在交流讨论中共同进步
若本书对您有所帮助,请在页面右上角点个 Star :star: 支持一下,谢谢!

View File

@ -12,7 +12,7 @@ int myMin(int a, int b) {
}
/* 求最大值 */
int myMax(int a, int b) {
return a < b ? a : b;
return a > b ? a : b;
}
/* 最大容量:贪心 */

View File

@ -32,7 +32,7 @@ HashMapOpenAddressing *newHashMapOpenAddressing() {
hashMap->capacity = 4;
hashMap->loadThres = 2.0 / 3.0;
hashMap->extendRatio = 2;
hashMap->buckets = (Pair **)malloc(sizeof(Pair *) * hashMap->capacity);
hashMap->buckets = (Pair **)calloc(hashMap->capacity, sizeof(Pair *));
hashMap->TOMBSTONE = (Pair *)malloc(sizeof(Pair));
hashMap->TOMBSTONE->key = -1;
hashMap->TOMBSTONE->val = "-1";
@ -151,7 +151,7 @@ void extend(HashMapOpenAddressing *hashMap) {
int oldCapacity = hashMap->capacity;
// 初始化扩容后的新哈希表
hashMap->capacity *= hashMap->extendRatio;
hashMap->buckets = (Pair **)malloc(sizeof(Pair *) * hashMap->capacity);
hashMap->buckets = (Pair **)calloc(hashMap->capacity, sizeof(Pair *));
hashMap->size = 0;
// 将键值对从原哈希表搬运至新哈希表
for (int i = 0; i < oldCapacity; i++) {

View File

@ -50,7 +50,7 @@ int rotHash(char *key) {
/* Driver Code */
int main() {
char *key = "Hello dsad3241241dsa123";
char *key = "Hello 算法";
int hash = addHash(key);
printf("加法哈希值为 %d\n", hash);

View File

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

View File

@ -65,6 +65,7 @@ void countingSort(int nums[], int size) {
// 使用结果数组 res 覆盖原数组 nums
memcpy(nums, res, size * sizeof(int));
// 5. 释放内存
free(res);
free(counter);
}

View File

@ -43,7 +43,7 @@ void mergeSort(int *nums, int left, int right) {
if (left >= right)
return; // 当子数组长度为 1 时终止递归
// 划分阶段
int mid = (left + right) / 2; // 计算中点
int mid = left + (right - left) / 2; // 计算中点
mergeSort(nums, left, mid); // 递归左子数组
mergeSort(nums, mid + 1, right); // 递归右子数组
// 合并阶段

View File

@ -89,9 +89,9 @@ void quickSortMedian(int nums[], int left, int right) {
quickSortMedian(nums, pivot + 1, right);
}
// 以下为递归优化的快速排序
// 以下为递归深度优化的快速排序
/* 快速排序(递归优化) */
/* 快速排序(递归深度优化) */
void quickSortTailCall(int nums[], int left, int right) {
// 子数组长度为 1 时终止
while (left < right) {
@ -127,10 +127,10 @@ int main() {
printf("快速排序(中位基准数优化)完成后 nums = ");
printArray(nums1, size);
/* 快速排序(递归优化) */
/* 快速排序(递归深度优化) */
int nums2[] = {2, 4, 1, 0, 3, 5};
quickSortTailCall(nums2, 0, size - 1);
printf("快速排序(递归优化)完成后 nums = ");
printf("快速排序(递归深度优化)完成后 nums = ");
printArray(nums1, size);
return 0;

View File

@ -16,6 +16,7 @@ int digit(int num, int exp) {
void countingSortDigit(int nums[], int size, int exp) {
// 十进制的位范围为 0~9 ,因此需要长度为 10 的桶数组
int *counter = (int *)malloc((sizeof(int) * 10));
memset(counter, 0, sizeof(int) * 10); // 初始化为 0 以支持后续内存释放
// 统计 0~9 各数字的出现次数
for (int i = 0; i < size; i++) {
// 获取 nums[i] 第 k 位,记为 d
@ -39,13 +40,16 @@ void countingSortDigit(int nums[], int size, int exp) {
for (int i = 0; i < size; i++) {
nums[i] = res[i];
}
// 释放内存
free(res);
free(counter);
}
/* 基数排序 */
void radixSort(int nums[], int size) {
// 获取数组的最大元素,用于判断最大位数
int max = INT32_MIN;
for (size_t i = 0; i < size - 1; i++) {
for (int i = 0; i < size; i++) {
if (nums[i] > max) {
max = nums[i];
}

View File

@ -111,16 +111,29 @@ int popLast(ArrayDeque *deque) {
return num;
}
/* 返回数组用于打印 */
int *toArray(ArrayDeque *deque, int *queSize) {
*queSize = deque->queSize;
int *res = (int *)calloc(deque->queSize, sizeof(int));
int j = deque->front;
for (int i = 0; i < deque->queSize; i++) {
res[i] = deque->nums[j % deque->queCapacity];
j++;
}
return res;
}
/* Driver Code */
int main() {
/* 初始化队列 */
int capacity = 10;
int queSize;
ArrayDeque *deque = newArrayDeque(capacity);
pushLast(deque, 3);
pushLast(deque, 2);
pushLast(deque, 5);
printf("双向队列 deque = ");
printArray(deque->nums, deque->queSize);
printArray(toArray(deque, &queSize), queSize);
/* 访问元素 */
int peekFirstNum = peekFirst(deque);
@ -131,18 +144,18 @@ int main() {
/* 元素入队 */
pushLast(deque, 4);
printf("元素 4 队尾入队后 deque = ");
printArray(deque->nums, deque->queSize);
printArray(toArray(deque, &queSize), queSize);
pushFirst(deque, 1);
printf("元素 1 队首入队后 deque = ");
printArray(deque->nums, deque->queSize);
printArray(toArray(deque, &queSize), queSize);
/* 元素出队 */
int popLastNum = popLast(deque);
printf("队尾出队元素 = %d ,队尾出队后 deque= ", popLastNum);
printArray(deque->nums, deque->queSize);
printArray(toArray(deque, &queSize), queSize);
int popFirstNum = popFirst(deque);
printf("队首出队元素 = %d ,队首出队后 deque= ", popFirstNum);
printArray(deque->nums, deque->queSize);
printArray(toArray(deque, &queSize), queSize);
/* 获取队列的长度 */
int dequeSize = size(deque);
@ -156,4 +169,4 @@ int main() {
delArrayDeque(deque);
return 0;
}
}

View File

@ -74,10 +74,23 @@ int pop(ArrayQueue *queue) {
return num;
}
/* 返回数组用于打印 */
int *toArray(ArrayQueue *queue, int *queSize) {
*queSize = queue->queSize;
int *res = (int *)calloc(queue->queSize, sizeof(int));
int j = queue->front;
for (int i = 0; i < queue->queSize; i++) {
res[i] = queue->nums[j % queue->queCapacity];
j++;
}
return res;
}
/* Driver Code */
int main() {
/* 初始化队列 */
int capacity = 10;
int queSize;
ArrayQueue *queue = newArrayQueue(capacity);
/* 元素入队 */
@ -87,7 +100,7 @@ int main() {
push(queue, 5);
push(queue, 4);
printf("队列 queue = ");
printArray(queue->nums, queue->queSize);
printArray(toArray(queue, &queSize), queSize);
/* 访问队首元素 */
int peekNum = peek(queue);
@ -96,7 +109,7 @@ int main() {
/* 元素出队 */
peekNum = pop(queue);
printf("出队元素 pop = %d ,出队后 queue = ", peekNum);
printArray(queue->nums, queue->queSize);
printArray(toArray(queue, &queSize), queSize);
/* 获取队列的长度 */
int queueSize = size(queue);
@ -111,11 +124,11 @@ int main() {
push(queue, i);
pop(queue);
printf("第 %d 轮入队 + 出队后 queue = ", i);
printArray(queue->nums, queue->queSize);
printArray(toArray(queue, &queSize), queSize);
}
// 释放内存
delArrayQueue(queue);
return 0;
}
}

View File

@ -90,11 +90,11 @@ int main() {
/* 获取栈的长度 */
int size = stack->size;
printf("栈的长度 size = %d\n", size);
printf("栈的长度 size = %d\n", size);
/* 判断是否为空 */
bool empty = isEmpty(stack);
printf("栈是否为空 = %stack\n", empty ? "true" : "false");
printf("栈是否为空 = %s\n", empty ? "true" : "false");
// 释放内存
delArrayStack(stack);

View File

@ -4,8 +4,8 @@
* Author: MolDuM (moldum@163.com)Reanon (793584285@qq.com)
*/
#ifndef C_INCLUDE_H
#define C_INCLUDE_H
#ifndef COMMON_H
#define COMMON_H
#include <assert.h>
#include <stdbool.h>
@ -33,4 +33,4 @@ extern "C" {
}
#endif
#endif // C_INCLUDE_H
#endif // COMMON_H

View File

@ -12,7 +12,7 @@
vector<Vertex *> graphBFS(GraphAdjList &graph, Vertex *startVet) {
// 顶点遍历序列
vector<Vertex *> res;
// 哈希,用于记录已被访问过的顶点
// 哈希集合,用于记录已被访问过的顶点
unordered_set<Vertex *> visited = {startVet};
// 队列用于实现 BFS
queue<Vertex *> que;

View File

@ -25,7 +25,7 @@ void dfs(GraphAdjList &graph, unordered_set<Vertex *> &visited, vector<Vertex *>
vector<Vertex *> graphDFS(GraphAdjList &graph, Vertex *startVet) {
// 顶点遍历序列
vector<Vertex *> res;
// 哈希,用于记录已被访问过的顶点
// 哈希集合,用于记录已被访问过的顶点
unordered_set<Vertex *> visited;
dfs(graph, visited, res, startVet);
return res;

View File

@ -48,7 +48,7 @@ int rotHash(string key) {
/* Driver Code */
int main() {
string key = "Hello dsad3241241dsa123";
string key = "Hello 算法";
int hash = addHash(key);
cout << "加法哈希值为 " << hash << endl;

View File

@ -39,7 +39,7 @@ void mergeSort(vector<int> &nums, int left, int right) {
if (left >= right)
return; // 当子数组长度为 1 时终止递归
// 划分阶段
int mid = (left + right) / 2; // 计算中点
int mid = left + (right - left) / 2; // 计算中点
mergeSort(nums, left, mid); // 递归左子数组
mergeSort(nums, mid + 1, right); // 递归右子数组
// 合并阶段

View File

@ -9,26 +9,19 @@
/* 快速排序类 */
class QuickSort {
private:
/* 元素交换 */
static void swap(vector<int> &nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
/* 哨兵划分 */
static int partition(vector<int> &nums, int left, int right) {
// 以 nums[left] 为基准数
int i = left, j = right;
while (i < j) {
while (i < j && nums[j] >= nums[left])
j--; // 从右向左找首个小于基准数的元素
j--; // 从右向左找首个小于基准数的元素
while (i < j && nums[i] <= nums[left])
i++; // 从左向右找首个大于基准数的元素
swap(nums, i, j); // 交换这两个元素
i++; // 从左向右找首个大于基准数的元素
swap(nums[i], nums[j]); // 交换这两个元素
}
swap(nums, i, left); // 将基准数交换至两子数组的分界线
return i; // 返回基准数的索引
swap(nums[i], nums[left]); // 将基准数交换至两子数组的分界线
return i; // 返回基准数的索引
}
public:
@ -48,13 +41,6 @@ class QuickSort {
/* 快速排序类(中位基准数优化) */
class QuickSortMedian {
private:
/* 元素交换 */
static void swap(vector<int> &nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
/* 选取三个候选元素的中位数 */
static int medianThree(vector<int> &nums, int left, int mid, int right) {
int l = nums[left], m = nums[mid], r = nums[right];
@ -70,18 +56,18 @@ class QuickSortMedian {
// 选取三个候选元素的中位数
int med = medianThree(nums, left, (left + right) / 2, right);
// 将中位数交换至数组最左端
swap(nums, left, med);
swap(nums[left], nums[med]);
// 以 nums[left] 为基准数
int i = left, j = right;
while (i < j) {
while (i < j && nums[j] >= nums[left])
j--; // 从右向左找首个小于基准数的元素
j--; // 从右向左找首个小于基准数的元素
while (i < j && nums[i] <= nums[left])
i++; // 从左向右找首个大于基准数的元素
swap(nums, i, j); // 交换这两个元素
i++; // 从左向右找首个大于基准数的元素
swap(nums[i], nums[j]); // 交换这两个元素
}
swap(nums, i, left); // 将基准数交换至两子数组的分界线
return i; // 返回基准数的索引
swap(nums[i], nums[left]); // 将基准数交换至两子数组的分界线
return i; // 返回基准数的索引
}
public:
@ -98,33 +84,26 @@ class QuickSortMedian {
}
};
/* 快速排序类(递归优化) */
/* 快速排序类(递归深度优化) */
class QuickSortTailCall {
private:
/* 元素交换 */
static void swap(vector<int> &nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
/* 哨兵划分 */
static int partition(vector<int> &nums, int left, int right) {
// 以 nums[left] 为基准数
int i = left, j = right;
while (i < j) {
while (i < j && nums[j] >= nums[left])
j--; // 从右向左找首个小于基准数的元素
j--; // 从右向左找首个小于基准数的元素
while (i < j && nums[i] <= nums[left])
i++; // 从左向右找首个大于基准数的元素
swap(nums, i, j); // 交换这两个元素
i++; // 从左向右找首个大于基准数的元素
swap(nums[i], nums[j]); // 交换这两个元素
}
swap(nums, i, left); // 将基准数交换至两子数组的分界线
return i; // 返回基准数的索引
swap(nums[i], nums[left]); // 将基准数交换至两子数组的分界线
return i; // 返回基准数的索引
}
public:
/* 快速排序(递归优化) */
/* 快速排序(递归深度优化) */
static void quickSort(vector<int> &nums, int left, int right) {
// 子数组长度为 1 时终止
while (left < right) {
@ -156,10 +135,10 @@ int main() {
cout << "快速排序(中位基准数优化)完成后 nums = ";
printVector(nums1);
/* 快速排序(递归优化) */
/* 快速排序(递归深度优化) */
vector<int> nums2 = {2, 4, 1, 0, 3, 5};
QuickSortTailCall::quickSort(nums2, 0, nums2.size() - 1);
cout << "快速排序(递归优化)完成后 nums = ";
cout << "快速排序(递归深度优化)完成后 nums = ";
printVector(nums2);
return 0;

View File

@ -115,9 +115,9 @@ int main() {
int i = 1;
int l = abt.left(i), r = abt.right(i), p = abt.parent(i);
cout << "\n当前节点的索引为 " << i << ",值为 " << abt.val(i) << "\n";
cout << "其左子节点的索引为 " << l << ",值为 " << (l != INT_MAX ? to_string(abt.val(l)) : "nullptr") << "\n";
cout << "其右子节点的索引为 " << r << ",值为 " << (r != INT_MAX ? to_string(abt.val(r)) : "nullptr") << "\n";
cout << "其父节点的索引为 " << p << ",值为 " << (p != INT_MAX ? to_string(abt.val(p)) : "nullptr") << "\n";
cout << "其左子节点的索引为 " << l << ",值为 " << (abt.val(l) != INT_MAX ? to_string(abt.val(l)) : "nullptr") << "\n";
cout << "其右子节点的索引为 " << r << ",值为 " << (abt.val(r) != INT_MAX ? to_string(abt.val(r)) : "nullptr") << "\n";
cout << "其父节点的索引为 " << p << ",值为 " << (abt.val(p) != INT_MAX ? to_string(abt.val(p)) : "nullptr") << "\n";
// 遍历树
vector<int> res = abt.levelOrder();

View File

@ -105,7 +105,7 @@ public class min_path_sum {
// 暴力搜索
int res = MinPathSumDFS(grid, n - 1, m - 1);
Console.WriteLine("从左上角到右下角的小路径和为 " + res);
Console.WriteLine("从左上角到右下角的小路径和为 " + res);
// 记忆化搜索
int[][] mem = new int[n][];
@ -114,14 +114,14 @@ public class min_path_sum {
Array.Fill(mem[i], -1);
}
res = MinPathSumDFSMem(grid, mem, n - 1, m - 1);
Console.WriteLine("从左上角到右下角的小路径和为 " + res);
Console.WriteLine("从左上角到右下角的小路径和为 " + res);
// 动态规划
res = MinPathSumDP(grid);
Console.WriteLine("从左上角到右下角的小路径和为 " + res);
Console.WriteLine("从左上角到右下角的小路径和为 " + res);
// 空间优化后的动态规划
res = MinPathSumDPComp(grid);
Console.WriteLine("从左上角到右下角的小路径和为 " + res);
Console.WriteLine("从左上角到右下角的小路径和为 " + res);
}
}

View File

@ -12,7 +12,7 @@ public class graph_bfs {
List<Vertex> GraphBFS(GraphAdjList graph, Vertex startVet) {
// 顶点遍历序列
List<Vertex> res = [];
// 哈希,用于记录已被访问过的顶点
// 哈希集合,用于记录已被访问过的顶点
HashSet<Vertex> visited = [startVet];
// 队列用于实现 BFS
Queue<Vertex> que = new();

View File

@ -26,7 +26,7 @@ public class graph_dfs {
List<Vertex> GraphDFS(GraphAdjList graph, Vertex startVet) {
// 顶点遍历序列
List<Vertex> res = [];
// 哈希,用于记录已被访问过的顶点
// 哈希集合,用于记录已被访问过的顶点
HashSet<Vertex> visited = [];
DFS(graph, visited, res, startVet);
return res;

View File

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

View File

@ -39,7 +39,7 @@ public class merge_sort {
// 终止条件
if (left >= right) return; // 当子数组长度为 1 时终止递归
// 划分阶段
int mid = (left + right) / 2; // 计算中点
int mid = left + (right - left) / 2; // 计算中点
MergeSort(nums, left, mid); // 递归左子数组
MergeSort(nums, mid + 1, right); // 递归右子数组
// 合并阶段

View File

@ -89,7 +89,7 @@ class QuickSortMedian {
}
}
/* 快速排序类(递归优化) */
/* 快速排序类(递归深度优化) */
class QuickSortTailCall {
/* 元素交换 */
static void Swap(int[] nums, int i, int j) {
@ -111,7 +111,7 @@ class QuickSortTailCall {
return i; // 返回基准数的索引
}
/* 快速排序(递归优化) */
/* 快速排序(递归深度优化) */
public static void QuickSort(int[] nums, int left, int right) {
// 子数组长度为 1 时终止
while (left < right) {
@ -142,9 +142,9 @@ public class quick_sort {
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));
Console.WriteLine("快速排序(递归深度优化)完成后 nums2 = " + string.Join(",", nums2));
}
}

View File

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

View File

@ -14,7 +14,7 @@ List<Vertex> graphBFS(GraphAdjList graph, Vertex startVet) {
// 使便
//
List<Vertex> res = [];
// 访
// 访
Set<Vertex> visited = {};
visited.add(startVet);
// BFS

View File

@ -30,7 +30,7 @@ void dfs(
List<Vertex> graphDFS(GraphAdjList graph, Vertex startVet) {
//
List<Vertex> res = [];
// 访
// 访
Set<Vertex> visited = {};
dfs(graph, visited, res, startVet);
return res;

View File

@ -36,7 +36,7 @@ void mergeSort(List<int> nums, int left, int right) {
//
if (left >= right) return; // 1
//
int mid = (left + right) ~/ 2; //
int mid = left + (right - left) ~/ 2; //
mergeSort(nums, left, mid); //
mergeSort(nums, mid + 1, right); //
//

View File

@ -86,7 +86,7 @@ class QuickSortMedian {
}
}
/* 快速排序类(递归优化) */
/* 快速排序类(递归深度优化) */
class QuickSortTailCall {
/* 元素交换 */
static void _swap(List<int> nums, int i, int j) {
@ -108,7 +108,7 @@ class QuickSortTailCall {
return i; //
}
/* 快速排序(递归优化) */
/* 快速排序(递归深度优化) */
static void quickSort(List<int> nums, int left, int right) {
// 1
while (left < right) {
@ -138,8 +138,8 @@ void main() {
QuickSortMedian.quickSort(nums1, 0, nums1.length - 1);
print("快速排序(中位基准数优化)完成后 nums1 = $nums1");
/* 快速排序(递归优化) */
/* 快速排序(递归深度优化) */
List<int> nums2 = [2, 4, 1, 0, 3, 5];
QuickSortTailCall.quickSort(nums2, 0, nums2.length - 1);
print("快速排序(递归优化)完成后 nums2 = $nums2");
print("快速排序(递归深度优化)完成后 nums2 = $nums2");
}

View File

@ -15,6 +15,7 @@ func backtrack(row, n int, state *[][]string, res *[][][]string, cols, diags1, d
}
*res = append(*res, newState)
return
}
// 遍历所有列
for col := 0; col < n; col++ {

View File

@ -23,7 +23,7 @@ func backtrackII(state *[]int, choices *[]int, selected *[]bool, res *[][]int) {
(*selected)[i] = true
*state = append(*state, choice)
// 进行下一轮选择
backtrackI(state, choices, selected, res)
backtrackII(state, choices, selected, res)
// 回退:撤销选择,恢复到之前的状态
(*selected)[i] = false
*state = (*state)[:len(*state)-1]

View File

@ -18,7 +18,7 @@ func dfs(nums []int, target, i, j int) int {
// 递归子问题 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 {

View File

@ -20,7 +20,7 @@ func TestMinPathSum(t *testing.T) {
// 暴力搜索
res := minPathSumDFS(grid, n-1, m-1)
fmt.Printf("从左上角到右下角的小路径和为 %d\n", res)
fmt.Printf("从左上角到右下角的小路径和为 %d\n", res)
// 记忆化搜索
mem := make([][]int, n)
@ -31,13 +31,13 @@ func TestMinPathSum(t *testing.T) {
}
}
res = minPathSumDFSMem(grid, mem, n-1, m-1)
fmt.Printf("从左上角到右下角的小路径和为 %d\n", res)
fmt.Printf("从左上角到右下角的小路径和为 %d\n", res)
// 动态规划
res = minPathSumDP(grid)
fmt.Printf("从左上角到右下角的小路径和为 %d\n", res)
fmt.Printf("从左上角到右下角的小路径和为 %d\n", res)
// 空间优化后的动态规划
res = minPathSumDPComp(grid)
fmt.Printf("从左上角到右下角的小路径和为 %d\n", res)
fmt.Printf("从左上角到右下角的小路径和为 %d\n", res)
}

View File

@ -13,7 +13,7 @@ import (
func graphBFS(g *graphAdjList, startVet Vertex) []Vertex {
// 顶点遍历序列
res := make([]Vertex, 0)
// 哈希,用于记录已被访问过的顶点
// 哈希集合,用于记录已被访问过的顶点
visited := make(map[Vertex]struct{})
visited[startVet] = struct{}{}
// 队列用于实现 BFS, 使用切片模拟队列

View File

@ -28,7 +28,7 @@ func dfs(g *graphAdjList, visited map[Vertex]struct{}, res *[]Vertex, vet Vertex
func graphDFS(g *graphAdjList, startVet Vertex) []Vertex {
// 顶点遍历序列
res := make([]Vertex, 0)
// 哈希,用于记录已被访问过的顶点
// 哈希集合,用于记录已被访问过的顶点
visited := make(map[Vertex]struct{})
dfs(g, visited, &res, startVet)
// 返回顶点遍历序列

View File

@ -9,7 +9,7 @@ func twoSumBruteForce(nums []int, target int) []int {
size := len(nums)
// 两层循环,时间复杂度为 O(n^2)
for i := 0; i < size-1; i++ {
for j := i + 1; i < size; j++ {
for j := i + 1; j < size; j++ {
if nums[i]+nums[j] == target {
return []int{i, j}
}

View File

@ -16,5 +16,5 @@ func TestBubbleSort(t *testing.T) {
nums1 := []int{4, 1, 3, 1, 5, 2}
bubbleSortWithFlag(nums1)
fmt.Println("冒泡排序完成后 nums1 = ", nums)
fmt.Println("冒泡排序完成后 nums1 = ", nums1)
}

View File

@ -46,7 +46,7 @@ func mergeSort(nums []int, left, right int) {
return
}
// 划分阶段
mid := (left + right) / 2
mid := left + (right - left) / 2
mergeSort(nums, left, mid)
mergeSort(nums, mid+1, right)
// 合并阶段

View File

@ -10,7 +10,7 @@ type quickSort struct{}
// 快速排序(中位基准数优化)
type quickSortMedian struct{}
// 快速排序(递归优化)
// 快速排序(递归深度优化)
type quickSortTailCall struct{}
/* 哨兵划分 */
@ -112,7 +112,7 @@ func (q *quickSortTailCall) partition(nums []int, left, right int) int {
return i // 返回基准数的索引
}
/* 快速排序(递归优化)*/
/* 快速排序(递归深度优化)*/
func (q *quickSortTailCall) quickSort(nums []int, left, right int) {
// 子数组长度为 1 时终止
for left < right {

View File

@ -25,10 +25,10 @@ func TestQuickSortMedian(t *testing.T) {
fmt.Println("快速排序(中位基准数优化)完成后 nums = ", nums)
}
// 快速排序(递归优化)
// 快速排序(递归深度优化)
func TestQuickSortTailCall(t *testing.T) {
q := quickSortTailCall{}
nums := []int{4, 1, 3, 1, 5, 2}
q.quickSort(nums, 0, len(nums)-1)
fmt.Println("快速排序(递归优化)完成后 nums = ", nums)
fmt.Println("快速排序(递归深度优化)完成后 nums = ", nums)
}

View File

@ -72,6 +72,9 @@ func (q *arrayDeque) pushLast(num int) {
/* 队首出队 */
func (q *arrayDeque) popFirst() any {
num := q.peekFirst()
if num == nil {
return nil
}
// 队首指针向后移动一位
q.front = q.index(q.front + 1)
q.queSize--
@ -81,6 +84,9 @@ func (q *arrayDeque) popFirst() any {
/* 队尾出队 */
func (q *arrayDeque) popLast() any {
num := q.peekLast()
if num == nil {
return nil
}
q.queSize--
return num
}

View File

@ -49,6 +49,10 @@ func (q *arrayQueue) push(num int) {
/* 出队 */
func (q *arrayQueue) pop() any {
num := q.peek()
if num == nil {
return nil
}
// 队首指针向后移动一位,若越过尾部,则返回到数组头部
q.front = (q.front + 1) % q.queCapacity
q.queSize--

View File

@ -46,9 +46,13 @@ func TestQueue(t *testing.T) {
}
func TestArrayQueue(t *testing.T) {
// 初始化队列,使用队列的通用接口
capacity := 10
queue := newArrayQueue(capacity)
if queue.pop() != nil {
t.Errorf("want:%v,got:%v", nil, queue.pop())
}
// 元素入队
queue.push(1)

View File

@ -15,7 +15,7 @@ public class graph_bfs {
static List<Vertex> graphBFS(GraphAdjList graph, Vertex startVet) {
// 顶点遍历序列
List<Vertex> res = new ArrayList<>();
// 哈希用于记录已被访问过的顶点
// 哈希集合用于记录已被访问过的顶点
Set<Vertex> visited = new HashSet<>();
visited.add(startVet);
// 队列用于实现 BFS

View File

@ -28,7 +28,7 @@ public class graph_dfs {
static List<Vertex> graphDFS(GraphAdjList graph, Vertex startVet) {
// 顶点遍历序列
List<Vertex> res = new ArrayList<>();
// 哈希用于记录已被访问过的顶点
// 哈希集合用于记录已被访问过的顶点
Set<Vertex> visited = new HashSet<>();
dfs(graph, visited, res, startVet);
return res;

View File

@ -42,7 +42,7 @@ public class merge_sort {
if (left >= right)
return; // 当子数组长度为 1 时终止递归
// 划分阶段
int mid = (left + right) / 2; // 计算中点
int mid = left + (right - left) / 2; // 计算中点
mergeSort(nums, left, mid); // 递归左子数组
mergeSort(nums, mid + 1, right); // 递归右子数组
// 合并阶段

View File

@ -96,7 +96,7 @@ class QuickSortMedian {
}
}
/* 快速排序类(递归优化) */
/* 快速排序类(递归深度优化) */
class QuickSortTailCall {
/* 元素交换 */
static void swap(int[] nums, int i, int j) {
@ -120,7 +120,7 @@ class QuickSortTailCall {
return i; // 返回基准数的索引
}
/* 快速排序(递归优化) */
/* 快速排序(递归深度优化) */
public static void quickSort(int[] nums, int left, int right) {
// 子数组长度为 1 时终止
while (left < right) {
@ -150,9 +150,9 @@ public class quick_sort {
QuickSortMedian.quickSort(nums1, 0, nums1.length - 1);
System.out.println("快速排序(中位基准数优化)完成后 nums1 = " + Arrays.toString(nums1));
/* 快速排序(递归优化) */
/* 快速排序(递归深度优化) */
int[] nums2 = { 2, 4, 1, 0, 3, 5 };
QuickSortTailCall.quickSort(nums2, 0, nums2.length - 1);
System.out.println("快速排序(递归优化)完成后 nums2 = " + Arrays.toString(nums2));
System.out.println("快速排序(递归深度优化)完成后 nums2 = " + Arrays.toString(nums2));
}
}

View File

@ -70,7 +70,7 @@ class MyList {
remove(index) {
if (index < 0 || index >= this.#size) throw new Error('索引越界');
let num = this.#arr[index];
// 将索引 index 之后的元素都向前移动一位
// 将索引 index 之后的元素都向前移动一位
for (let j = index; j < this.#size - 1; j++) {
this.#arr[j] = this.#arr[j + 1];
}

View File

@ -31,7 +31,7 @@ function coinChangeDP(coins, amt) {
return dp[n][amt] !== MAX ? dp[n][amt] : -1;
}
/* 零钱兑换:状态压缩后的动态规划 */
/* 零钱兑换:空间优化后的动态规划 */
function coinChangeDPComp(coins, amt) {
const n = coins.length;
const MAX = amt + 1;
@ -61,6 +61,6 @@ const amt = 4;
let res = coinChangeDP(coins, amt);
console.log(`凑到目标金额所需的最少硬币数量为 ${res}`);
// 状态压缩后的动态规划
// 空间优化后的动态规划
res = coinChangeDPComp(coins, amt);
console.log(`凑到目标金额所需的最少硬币数量为 ${res}`);

View File

@ -30,7 +30,7 @@ function coinChangeIIDP(coins, amt) {
return dp[n][amt];
}
/* 零钱兑换 II状态压缩后的动态规划 */
/* 零钱兑换 II空间优化后的动态规划 */
function coinChangeIIDPComp(coins, amt) {
const n = coins.length;
// 初始化 dp 表
@ -59,6 +59,6 @@ const amt = 5;
let res = coinChangeIIDP(coins, amt);
console.log(`凑出目标金额的硬币组合数量为 ${res}`);
// 状态压缩后的动态规划
// 空间优化后的动态规划
res = coinChangeIIDPComp(coins, amt);
console.log(`凑出目标金额的硬币组合数量为 ${res}`);

View File

@ -82,7 +82,7 @@ function editDistanceDP(s, t) {
return dp[n][m];
}
/* 编辑距离:状态压缩后的动态规划 */
/* 编辑距离:空间优化后的动态规划 */
function editDistanceDPComp(s, t) {
const n = s.length,
m = t.length;
@ -130,6 +130,6 @@ console.log(`将 ${s} 更改为 ${t} 最少需要编辑 ${res} 步`);
res = editDistanceDP(s, t);
console.log(`${s} 更改为 ${t} 最少需要编辑 ${res}`);
// 状态压缩后的动态规划
// 空间优化后的动态规划
res = editDistanceDPComp(s, t);
console.log(`${s} 更改为 ${t} 最少需要编辑 ${res}`);

View File

@ -69,7 +69,7 @@ function knapsackDP(wgt, val, cap) {
return dp[n][cap];
}
/* 0-1 背包:状态压缩后的动态规划 */
/* 0-1 背包:空间优化后的动态规划 */
function knapsackDPComp(wgt, val, cap) {
const n = wgt.length;
// 初始化 dp 表
@ -108,6 +108,6 @@ console.log(`不超过背包容量的最大物品价值为 ${res}`);
res = knapsackDP(wgt, val, cap);
console.log(`不超过背包容量的最大物品价值为 ${res}`);
// 状态压缩后的动态规划
// 空间优化后的动态规划
res = knapsackDPComp(wgt, val, cap);
console.log(`不超过背包容量的最大物品价值为 ${res}`);

View File

@ -22,7 +22,7 @@ function minCostClimbingStairsDP(cost) {
return dp[n];
}
/* 爬楼梯最小代价:状态压缩后的动态规划 */
/* 爬楼梯最小代价:空间优化后的动态规划 */
function minCostClimbingStairsDPComp(cost) {
const n = cost.length - 1;
if (n === 1 || n === 2) {

View File

@ -69,7 +69,7 @@ function minPathSumDP(grid) {
return dp[n - 1][m - 1];
}
/* 最小路径和:状态压缩后的动态规划 */
/* 最小路径和:空间优化后的动态规划 */
function minPathSumDPComp(grid) {
const n = grid.length,
m = grid[0].length;
@ -116,6 +116,6 @@ console.log(`从左上角到右下角的最小路径和为 ${res}`);
res = minPathSumDP(grid);
console.log(`从左上角到右下角的最小路径和为 ${res}`);
// 状态压缩后的动态规划
// 空间优化后的动态规划
res = minPathSumDPComp(grid);
console.log(`从左上角到右下角的最小路径和为 ${res}`);

View File

@ -29,7 +29,7 @@ function unboundedKnapsackDP(wgt, val, cap) {
return dp[n][cap];
}
/* 完全背包:状态压缩后的动态规划 */
/* 完全背包:空间优化后的动态规划 */
function unboundedKnapsackDPComp(wgt, val, cap) {
const n = wgt.length;
// 初始化 dp 表
@ -58,6 +58,6 @@ const cap = 4;
let res = unboundedKnapsackDP(wgt, val, cap);
console.log(`不超过背包容量的最大物品价值为 ${res}`);
// 状态压缩后的动态规划
// 空间优化后的动态规划
res = unboundedKnapsackDPComp(wgt, val, cap);
console.log(`不超过背包容量的最大物品价值为 ${res}`);

View File

@ -46,7 +46,8 @@ class GraphAdjList {
if (
!this.adjList.has(vet1) ||
!this.adjList.has(vet2) ||
vet1 === vet2
vet1 === vet2 ||
this.adjList.get(vet1).indexOf(vet2) === -1
) {
throw new Error('Illegal Argument Exception');
}

View File

@ -12,7 +12,7 @@ const { Vertex } = require('../modules/Vertex');
function graphBFS(graph, startVet) {
// 顶点遍历序列
const res = [];
// 哈希,用于记录已被访问过的顶点
// 哈希集合,用于记录已被访问过的顶点
const visited = new Set();
visited.add(startVet);
// 队列用于实现 BFS

View File

@ -27,7 +27,7 @@ function dfs(graph, visited, res, vet) {
function graphDFS(graph, startVet) {
// 顶点遍历序列
const res = [];
// 哈希,用于记录已被访问过的顶点
// 哈希集合,用于记录已被访问过的顶点
const visited = new Set();
dfs(graph, visited, res, startVet);
return res;

View File

@ -31,7 +31,7 @@ function xorHash(key) {
for (const c of key) {
hash ^= c.charCodeAt(0);
}
return hash & MODULUS;
return hash % MODULUS;
}
/* 旋转哈希 */

View File

@ -8,10 +8,7 @@
// 简单实现,无法用于排序对象
function countingSortNaive(nums) {
// 1. 统计数组最大元素 m
let m = 0;
for (const num of nums) {
m = Math.max(m, num);
}
let m = Math.max(...nums);
// 2. 统计各数字的出现次数
// counter[num] 代表 num 的出现次数
const counter = new Array(m + 1).fill(0);
@ -31,10 +28,7 @@ function countingSortNaive(nums) {
// 完整实现,可排序对象,并且是稳定排序
function countingSort(nums) {
// 1. 统计数组最大元素 m
let m = 0;
for (const num of nums) {
m = Math.max(m, num);
}
let m = Math.max(...nums);
// 2. 统计各数字的出现次数
// counter[num] 代表 num 的出现次数
const counter = new Array(m + 1).fill(0);

View File

@ -39,7 +39,7 @@ function mergeSort(nums, left, right) {
// 终止条件
if (left >= right) return; // 当子数组长度为 1 时终止递归
// 划分阶段
let mid = Math.floor((left + right) / 2); // 计算中点
let mid = Math.floor(left + (right - left) / 2); // 计算中点
mergeSort(nums, left, mid); // 递归左子数组
mergeSort(nums, mid + 1, right); // 递归右子数组
// 合并阶段

View File

@ -100,7 +100,7 @@ class QuickSortMedian {
}
}
/* 快速排序类(递归优化) */
/* 快速排序类(递归深度优化) */
class QuickSortTailCall {
/* 元素交换 */
swap(nums, i, j) {
@ -123,7 +123,7 @@ class QuickSortTailCall {
return i; // 返回基准数的索引
}
/* 快速排序(递归优化) */
/* 快速排序(递归深度优化) */
quickSort(nums, left, right) {
// 子数组长度为 1 时终止
while (left < right) {
@ -154,8 +154,8 @@ const quickSortMedian = new QuickSortMedian();
quickSortMedian.quickSort(nums1, 0, nums1.length - 1);
console.log('快速排序(中位基准数优化)完成后 nums =', nums1);
/* 快速排序(递归优化) */
/* 快速排序(递归深度优化) */
const nums2 = [2, 4, 1, 0, 3, 5];
const quickSortTailCall = new QuickSortTailCall();
quickSortTailCall.quickSort(nums2, 0, nums2.length - 1);
console.log('快速排序(递归优化)完成后 nums =', nums2);
console.log('快速排序(递归深度优化)完成后 nums =', nums2);

View File

@ -41,12 +41,7 @@ function countingSortDigit(nums, exp) {
/* 基数排序 */
function radixSort(nums) {
// 获取数组的最大元素,用于判断最大位数
let m = Number.MIN_VALUE;
for (const num of nums) {
if (num > m) {
m = num;
}
}
let m = Math.max(... nums);
// 按照从低位到高位的顺序遍历
for (let exp = 1; exp <= m; exp *= 10) {
// 对数组元素的第 k 位执行计数排序

View File

@ -0,0 +1,63 @@
import { bold, brightRed } from 'jsr:@std/fmt/colors';
import { expandGlob } from 'jsr:@std/fs';
import { relative, resolve } from 'jsr:@std/path';
/**
* @typedef {import('jsr:@std/fs').WalkEntry} WalkEntry
* @type {WalkEntry[]}
*/
const entries = [];
for await (const entry of expandGlob(
resolve(import.meta.dirname, './chapter_*/*.js')
)) {
entries.push(entry);
}
/** @type {{ status: Promise<Deno.CommandStatus>; stderr: ReadableStream<Uint8Array>; }[]} */
const processes = [];
for (const file of entries) {
const execute = new Deno.Command('node', {
args: [relative(import.meta.dirname, file.path)],
cwd: import.meta.dirname,
stdin: 'piped',
stdout: 'piped',
stderr: 'piped',
});
const process = execute.spawn();
processes.push({ status: process.status, stderr: process.stderr });
}
const results = await Promise.all(
processes.map(async (item) => {
const status = await item.status;
return { status, stderr: item.stderr };
})
);
/** @type {ReadableStream<Uint8Array>[]} */
const errors = [];
for (const result of results) {
if (!result.status.success) {
errors.push(result.stderr);
}
}
console.log(`Tested ${entries.length} files`);
console.log(`Found exception in ${errors.length} files`);
if (errors.length) {
console.log();
for (const error of errors) {
const reader = error.getReader();
const { value } = await reader.read();
const decoder = new TextDecoder();
console.log(`${bold(brightRed('error'))}: ${decoder.decode(value)}`);
}
throw new Error('Test failed');
}

View File

@ -14,7 +14,7 @@ import java.util.*
fun graphBFS(graph: GraphAdjList, startVet: Vertex): MutableList<Vertex?> {
// 顶点遍历序列
val res = mutableListOf<Vertex?>()
// 哈希,用于记录已被访问过的顶点
// 哈希集合,用于记录已被访问过的顶点
val visited = HashSet<Vertex>()
visited.add(startVet)
// 队列用于实现 BFS

View File

@ -31,7 +31,7 @@ fun dfs(
fun graphDFS(graph: GraphAdjList, startVet: Vertex?): MutableList<Vertex?> {
// 顶点遍历序列
val res = mutableListOf<Vertex?>()
// 哈希,用于记录已被访问过的顶点
// 哈希集合,用于记录已被访问过的顶点
val visited = HashSet<Vertex?>()
dfs(graph, visited, res, startVet)
return res

View File

@ -19,7 +19,7 @@ fun merge(nums: IntArray, left: Int, mid: Int, right: Int) {
while (i <= mid && j <= right) {
if (nums[i] <= nums[j])
tmp[k++] = nums[i++]
else
else
tmp[k++] = nums[j++]
}
// 将左子数组和右子数组的剩余元素复制到临时数组中
@ -40,7 +40,7 @@ fun mergeSort(nums: IntArray, left: Int, right: Int) {
// 终止条件
if (left >= right) return // 当子数组长度为 1 时终止递归
// 划分阶段
val mid = (left + right) / 2 // 计算中点
val mid = left + (right - left) / 2 // 计算中点
mergeSort(nums, left, mid) // 递归左子数组
mergeSort(nums, mid + 1, right) // 递归右子数组
// 合并阶段
@ -53,4 +53,4 @@ fun main() {
val nums = intArrayOf(7, 3, 2, 6, 0, 1, 5, 4)
mergeSort(nums, 0, nums.size - 1)
println("归并排序完成后 nums = ${nums.contentToString()}")
}
}

View File

@ -83,7 +83,7 @@ fun quickSortMedian(nums: IntArray, left: Int, right: Int) {
quickSort(nums, pivot + 1, right)
}
/* 快速排序(递归优化) */
/* 快速排序(递归深度优化) */
fun quickSortTailCall(nums: IntArray, left: Int, right: Int) {
// 子数组长度为 1 时终止
var l = left
@ -114,8 +114,8 @@ fun main() {
quickSortMedian(nums1, 0, nums1.size - 1)
println("快速排序(中位基准数优化)完成后 nums1 = ${nums1.contentToString()}")
/* 快速排序(递归优化) */
/* 快速排序(递归深度优化) */
val nums2 = intArrayOf(2, 4, 1, 0, 3, 5)
quickSortTailCall(nums2, 0, nums2.size - 1)
println("快速排序(递归优化)完成后 nums2 = ${nums2.contentToString()}")
println("快速排序(递归深度优化)完成后 nums2 = ${nums2.contentToString()}")
}

View File

@ -97,7 +97,9 @@ def linear_log_recur(n: int) -> int:
"""线性对数阶"""
if n <= 1:
return 1
count: int = linear_log_recur(n // 2) + linear_log_recur(n // 2)
# 一分为二,子问题的规模减小一半
count = linear_log_recur(n // 2) + linear_log_recur(n // 2)
# 当前子问题包含 n 个操作
for _ in range(n):
count += 1
return count
@ -120,32 +122,32 @@ if __name__ == "__main__":
n = 8
print("输入数据大小 n =", n)
count: int = constant(n)
count = constant(n)
print("常数阶的操作数量 =", count)
count: int = linear(n)
count = linear(n)
print("线性阶的操作数量 =", count)
count: int = array_traversal([0] * n)
count = array_traversal([0] * n)
print("线性阶(遍历数组)的操作数量 =", count)
count: int = quadratic(n)
count = quadratic(n)
print("平方阶的操作数量 =", count)
nums = [i for i in range(n, 0, -1)] # [n, n-1, ..., 2, 1]
count: int = bubble_sort(nums)
count = bubble_sort(nums)
print("平方阶(冒泡排序)的操作数量 =", count)
count: int = exponential(n)
count = exponential(n)
print("指数阶(循环实现)的操作数量 =", count)
count: int = exp_recur(n)
count = exp_recur(n)
print("指数阶(递归实现)的操作数量 =", count)
count: int = logarithmic(n)
count = logarithmic(n)
print("对数阶(循环实现)的操作数量 =", count)
count: int = log_recur(n)
count = log_recur(n)
print("对数阶(递归实现)的操作数量 =", count)
count: int = linear_log_recur(n)
count = linear_log_recur(n)
print("线性对数阶(递归实现)的操作数量 =", count)
count: int = factorial_recur(n)
count = factorial_recur(n)
print("阶乘阶(递归实现)的操作数量 =", count)

View File

@ -88,17 +88,17 @@ if __name__ == "__main__":
# 暴力搜索
res = min_path_sum_dfs(grid, n - 1, m - 1)
print(f"从左上角到右下角的小路径和为 {res}")
print(f"从左上角到右下角的小路径和为 {res}")
# 记忆化搜索
mem = [[-1] * m for _ in range(n)]
res = min_path_sum_dfs_mem(grid, mem, n - 1, m - 1)
print(f"从左上角到右下角的小路径和为 {res}")
print(f"从左上角到右下角的小路径和为 {res}")
# 动态规划
res = min_path_sum_dp(grid)
print(f"从左上角到右下角的小路径和为 {res}")
print(f"从左上角到右下角的小路径和为 {res}")
# 空间优化后的动态规划
res = min_path_sum_dp_comp(grid)
print(f"从左上角到右下角的小路径和为 {res}")
print(f"从左上角到右下角的小路径和为 {res}")

View File

@ -18,7 +18,7 @@ def graph_bfs(graph: GraphAdjList, start_vet: Vertex) -> list[Vertex]:
# 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点
# 顶点遍历序列
res = []
# 哈希,用于记录已被访问过的顶点
# 哈希集合,用于记录已被访问过的顶点
visited = set[Vertex]([start_vet])
# 队列用于实现 BFS
que = deque[Vertex]([start_vet])

View File

@ -29,7 +29,7 @@ def graph_dfs(graph: GraphAdjList, start_vet: Vertex) -> list[Vertex]:
# 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点
# 顶点遍历序列
res = []
# 哈希,用于记录已被访问过的顶点
# 哈希集合,用于记录已被访问过的顶点
visited = set[Vertex]()
dfs(graph, visited, res, start_vet)
return res

View File

@ -9,9 +9,7 @@ def counting_sort_naive(nums: list[int]):
"""计数排序"""
# 简单实现,无法用于排序对象
# 1. 统计数组最大元素 m
m = 0
for num in nums:
m = max(m, num)
m = max(nums)
# 2. 统计各数字的出现次数
# counter[num] 代表 num 的出现次数
counter = [0] * (m + 1)

View File

@ -41,7 +41,7 @@ def merge_sort(nums: list[int], left: int, right: int):
if left >= right:
return # 当子数组长度为 1 时终止递归
# 划分阶段
mid = (left + right) // 2 # 计算中点
mid = (left + right) // 2 # 计算中点
merge_sort(nums, left, mid) # 递归左子数组
merge_sort(nums, mid + 1, right) # 递归右子数组
# 合并阶段

View File

@ -79,7 +79,7 @@ class QuickSortMedian:
class QuickSortTailCall:
"""快速排序类(递归优化)"""
"""快速排序类(递归深度优化)"""
def partition(self, nums: list[int], left: int, right: int) -> int:
"""哨兵划分"""
@ -97,7 +97,7 @@ class QuickSortTailCall:
return i # 返回基准数的索引
def quick_sort(self, nums: list[int], left: int, right: int):
"""快速排序(递归优化)"""
"""快速排序(递归深度优化)"""
# 子数组长度为 1 时终止
while left < right:
# 哨兵划分操作
@ -123,7 +123,7 @@ if __name__ == "__main__":
QuickSortMedian().quick_sort(nums1, 0, len(nums1) - 1)
print("快速排序(中位基准数优化)完成后 nums =", nums1)
# 快速排序(递归优化)
# 快速排序(递归深度优化)
nums2 = [2, 4, 1, 0, 3, 5]
QuickSortTailCall().quick_sort(nums2, 0, len(nums2) - 1)
print("快速排序(递归优化)完成后 nums =", nums2)
print("快速排序(递归深度优化)完成后 nums =", nums2)

View File

@ -18,7 +18,7 @@ class ArrayStack:
def is_empty(self) -> bool:
"""判断栈是否为空"""
return self._stack == []
return self.size() == 0
def push(self, item: int):
"""入栈"""

View File

@ -30,7 +30,7 @@ class LinkedListDeque:
def is_empty(self) -> bool:
"""判断双向队列是否为空"""
return self.size() == 0
return self._size == 0
def push(self, num: int, is_front: bool):
"""入队操作"""
@ -69,7 +69,7 @@ class LinkedListDeque:
val: int = self._front.val # 暂存头节点值
# 删除头节点
fnext: ListNode | None = self._front.next
if fnext != None:
if fnext is not None:
fnext.prev = None
self._front.next = None
self._front = fnext # 更新头节点
@ -78,7 +78,7 @@ class LinkedListDeque:
val: int = self._rear.val # 暂存尾节点值
# 删除尾节点
rprev: ListNode | None = self._rear.prev
if rprev != None:
if rprev is not None:
rprev.next = None
self._rear.prev = None
self._rear = rprev # 更新尾节点

View File

@ -26,7 +26,7 @@ class LinkedListQueue:
def is_empty(self) -> bool:
"""判断队列是否为空"""
return not self._front
return self._size == 0
def push(self, num: int):
"""入队"""

View File

@ -25,7 +25,7 @@ class LinkedListStack:
def is_empty(self) -> bool:
"""判断栈是否为空"""
return not self._peek
return self._size == 0
def push(self, val: int):
"""入栈"""

View File

@ -22,7 +22,7 @@ class ArrayBinaryTree:
"""列表容量"""
return len(self._tree)
def val(self, i: int) -> int:
def val(self, i: int) -> int | None:
"""获取索引为 i 节点的值"""
# 若索引越界,则返回 None ,代表空位
if i < 0 or i >= self.size():

View File

@ -0,0 +1,61 @@
=begin
File: n_queens.rb
Created Time: 2024-05-21
Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
=end
### 回溯算法n 皇后 ###
def backtrack(row, n, state, res, cols, diags1, diags2)
# 当放置完所有行时,记录解
if row == n
res << state.map { |row| row.dup }
return
end
# 遍历所有列
for col in 0...n
# 计算该格子对应的主对角线和次对角线
diag1 = row - col + n - 1
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
end
end
end
### 求解 n 皇后 ###
def n_queens(n)
# 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
state = Array.new(n) { Array.new(n, "#") }
cols = Array.new(n, false) # 记录列是否有皇后
diags1 = Array.new(2 * n - 1, false) # 记录主对角线上是否有皇后
diags2 = Array.new(2 * n - 1, false) # 记录次对角线上是否有皇后
res = []
backtrack(0, n, state, res, cols, diags1, diags2)
res
end
### Driver Code ###
if __FILE__ == $0
n = 4
res = n_queens(n)
puts "输入棋盘长宽为 #{n}"
puts "皇后放置方案共有 #{res.length}"
for state in res
puts "--------------------"
for row in state
p row
end
end
end

View File

@ -0,0 +1,46 @@
=begin
File: permutations_i.rb
Created Time: 2024-05-22
Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
=end
### 回溯算法:全排列 I ###
def backtrack(state, choices, selected, res)
# 当状态长度等于元素数量时,记录解
if state.length == choices.length
res << state.dup
return
end
# 遍历所有选择
choices.each_with_index do |choice, i|
# 剪枝:不允许重复选择元素
unless selected[i]
# 尝试:做出选择,更新状态
selected[i] = true
state << choice
# 进行下一轮选择
backtrack(state, choices, selected, res)
# 回退:撤销选择,恢复到之前的状态
selected[i] = false
state.pop
end
end
end
### 全排列 I ###
def permutations_i(nums)
res = []
backtrack([], nums, Array.new(nums.length, false), res)
res
end
### Driver Code ###
if __FILE__ == $0
nums = [1, 2, 3]
res = permutations_i(nums)
puts "输入数组 nums = #{nums}"
puts "所有排列 res = #{res}"
end

View File

@ -0,0 +1,48 @@
=begin
File: permutations_ii.rb
Created Time: 2024-05-22
Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
=end
### 回溯算法:全排列 II ###
def backtrack(state, choices, selected, res)
# 当状态长度等于元素数量时,记录解
if state.length == choices.length
res << state.dup
return
end
# 遍历所有选择
duplicated = Set.new
choices.each_with_index do |choice, i|
# 剪枝:不允许重复选择元素 且 不允许重复选择相等元素
if !selected[i] && !duplicated.include?(choice)
# 尝试:做出选择,更新状态
duplicated.add(choice)
selected[i] = true
state << choice
# 进行下一轮选择
backtrack(state, choices, selected, res)
# 回退:撤销选择,恢复到之前的状态
selected[i] = false
state.pop
end
end
end
### 全排列 II ###
def permutations_ii(nums)
res = []
backtrack([], nums, Array.new(nums.length, false), res)
res
end
### Driver Code ###
if __FILE__ == $0
nums = [1, 2, 2]
res = permutations_ii(nums)
puts "输入数组 nums = #{nums}"
puts "所有排列 res = #{res}"
end

View File

@ -0,0 +1,33 @@
=begin
File: preorder_traversal_i_compact.rb
Created Time: 2024-05-22
Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
=end
require_relative '../utils/tree_node'
require_relative '../utils/print_util'
### 前序遍历:例题一 ###
def pre_order(root)
return unless root
# 记录解
$res << root if root.val == 7
pre_order(root.left)
pre_order(root.right)
end
### Driver Code ###
if __FILE__ == $0
root = arr_to_tree([1, 7, 3, 4, 5, 6, 7])
puts "\n初始化二叉树"
print_tree(root)
# 前序遍历
$res = []
pre_order(root)
puts "\n输出所有值为 7 的节点"
p $res.map { |node| node.val }
end

View File

@ -0,0 +1,41 @@
=begin
File: preorder_traversal_ii_compact.rb
Created Time: 2024-05-22
Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
=end
require_relative '../utils/tree_node'
require_relative '../utils/print_util'
### 前序遍历:例题二 ###
def pre_order(root)
return unless root
# 尝试
$path << root
# 记录解
$res << $path.dup if root.val == 7
pre_order(root.left)
pre_order(root.right)
# 回退
$path.pop
end
### Driver Code ###
if __FILE__ == $0
root = arr_to_tree([1, 7, 3, 4, 5, 6, 7])
puts "\n初始化二叉树"
print_tree(root)
# 前序遍历
$path, $res = [], []
pre_order(root)
puts "\n输出所有根节点到节点 7 的路径"
for path in $res
p path.map { |node| node.val }
end
end

View File

@ -0,0 +1,42 @@
=begin
File: preorder_traversal_iii_compact.rb
Created Time: 2024-05-22
Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
=end
require_relative '../utils/tree_node'
require_relative '../utils/print_util'
### 前序遍历:例题三 ###
def pre_order(root)
# 剪枝
return if !root || root.val == 3
# 尝试
$path.append(root)
# 记录解
$res << $path.dup if root.val == 7
pre_order(root.left)
pre_order(root.right)
# 回退
$path.pop
end
### Driver Code ###
if __FILE__ == $0
root = arr_to_tree([1, 7, 3, 4, 5, 6, 7])
puts "\n初始化二叉树"
print_tree(root)
# 前序遍历
$path, $res = [], []
pre_order(root)
puts "\n输出所有根节点到节点 7 的路径,路径中不包含值为 3 的节点"
for path in $res
p path.map { |node| node.val }
end
end

View File

@ -0,0 +1,68 @@
=begin
File: preorder_traversal_iii_template.rb
Created Time: 2024-05-22
Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
=end
require_relative '../utils/tree_node'
require_relative '../utils/print_util'
### 判断当前状态是否为解 ###
def is_solution?(state)
!state.empty? && state.last.val == 7
end
### 记录解 ###
def record_solution(state, res)
res << state.dup
end
### 判断在当前状态下,该选择是否合法 ###
def is_valid?(state, choice)
choice && choice.val != 3
end
### 更新状态 ###
def make_choice(state, choice)
state << choice
end
### 恢复状态 ###
def undo_choice(state, choice)
state.pop
end
### 回溯算法:例题三 ###
def backtrack(state, choices, res)
# 检查是否为解
record_solution(state, res) if is_solution?(state)
# 遍历所有选择
for choice in choices
# 剪枝:检查选择是否合法
if is_valid?(state, choice)
# 尝试:做出选择,更新状态
make_choice(state, choice)
# 进行下一轮选择
backtrack(state, [choice.left, choice.right], res)
# 回退:撤销选择,恢复到之前的状态
undo_choice(state, choice)
end
end
end
### Driver Code ###
if __FILE__ == $0
root = arr_to_tree([1, 7, 3, 4, 5, 6, 7])
puts "\n初始化二叉树"
print_tree(root)
# 回溯算法
res = []
backtrack([], [root], res)
puts "\n输出所有根节点到节点 7 的路径,要求路径中不包含值为 3 的节点"
for path in res
p path.map { |node| node.val }
end
end

View File

@ -0,0 +1,47 @@
=begin
File: subset_sum_i.rb
Created Time: 2024-05-22
Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
=end
### 回溯算法:子集和 I ###
def backtrack(state, target, choices, start, res)
# 子集和等于 target 时,记录解
if target.zero?
res << state.dup
return
end
# 遍历所有选择
# 剪枝二:从 start 开始遍历,避免生成重复子集
for i in start...choices.length
# 剪枝一:若子集和超过 target ,则直接结束循环
# 这是因为数组已排序,后边元素更大,子集和一定超过 target
break if target - choices[i] < 0
# 尝试:做出选择,更新 target, start
state << choices[i]
# 进行下一轮选择
backtrack(state, target - choices[i], choices, i, res)
# 回退:撤销选择,恢复到之前的状态
state.pop
end
end
### 求解子集和 I ###
def subset_sum_i(nums, target)
state = [] # 状态(子集)
nums.sort! # 对 nums 进行排序
start = 0 # 遍历起始点
res = [] # 结果列表(子集列表)
backtrack(state, target, nums, start, res)
res
end
### Driver Code ###
if __FILE__ == $0
nums = [3, 4, 5]
target = 9
res = subset_sum_i(nums, target)
puts "输入数组 = #{nums}, target = #{target}"
puts "所有和等于 #{target} 的子集 res = #{res}"
end

View File

@ -0,0 +1,46 @@
=begin
File: subset_sum_i_naive.rb
Created Time: 2024-05-22
Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
=end
### 回溯算法:子集和 I ###
def backtrack(state, target, total, choices, res)
# 子集和等于 target 时,记录解
if total == target
res << state.dup
return
end
# 遍历所有选择
for i in 0...choices.length
# 剪枝:若子集和超过 target ,则跳过该选择
next if total + choices[i] > target
# 尝试:做出选择,更新元素和 total
state << choices[i]
# 进行下一轮选择
backtrack(state, target, total + choices[i], choices, res)
# 回退:撤销选择,恢复到之前的状态
state.pop
end
end
### 求解子集和 I包含重复子集###
def subset_sum_i_naive(nums, target)
state = [] # 状态(子集)
total = 0 # 子集和
res = [] # 结果列表(子集列表)
backtrack(state, target, total, nums, res)
res
end
### Driver Code ###
if __FILE__ == $0
nums = [3, 4, 5]
target = 9
res = subset_sum_i_naive(nums, target)
puts "输入数组 nums = #{nums}, target = #{target}"
puts "所有和等于 #{target} 的子集 res = #{res}"
puts "请注意,该方法输出的结果包含重复集合"
end

View File

@ -0,0 +1,51 @@
=begin
File: subset_sum_ii.rb
Created Time: 2024-05-22
Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
=end
### 回溯算法:子集和 II ###
def backtrack(state, target, choices, start, res)
# 子集和等于 target 时,记录解
if target.zero?
res << state.dup
return
end
# 遍历所有选择
# 剪枝二:从 start 开始遍历,避免生成重复子集
# 剪枝三:从 start 开始遍历,避免重复选择同一元素
for i in start...choices.length
# 剪枝一:若子集和超过 target ,则直接结束循环
# 这是因为数组已排序,后边元素更大,子集和一定超过 target
break if target - choices[i] < 0
# 剪枝四:如果该元素与左边元素相等,说明该搜索分支重复,直接跳过
next if i > start && choices[i] == choices[i - 1]
# 尝试:做出选择,更新 target, start
state << choices[i]
# 进行下一轮选择
backtrack(state, target - choices[i], choices, i + 1, res)
# 回退:撤销选择,恢复到之前的状态
state.pop
end
end
### 求解子集和 II ###
def subset_sum_ii(nums, target)
state = [] # 状态(子集)
nums.sort! # 对 nums 进行排序
start = 0 # 遍历起始点
res = [] # 结果列表(子集列表)
backtrack(state, target, nums, start, res)
res
end
### Driver Code ###
if __FILE__ == $0
nums = [4, 4, 5]
target = 9
res = subset_sum_ii(nums, target)
puts "输入数组 nums = #{nums}, target = #{target}"
puts "所有和等于 #{target} 的子集 res = #{res}"
end

View File

@ -0,0 +1,42 @@
=begin
File: binary_search_recur.rb
Created Time: 2024-05-13
Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
=end
### 二分查找:问题 f(i, j) ###
def dfs(nums, target, i, j)
# 若区间为空,代表无目标元素,则返回 -1
return -1 if i > j
# 计算中点索引 m
m = (i + j) / 2
if nums[m] < target
# 递归子问题 f(m+1, j)
return dfs(nums, target, m + 1, j)
elsif nums[m] > target
# 递归子问题 f(i, m-1)
return dfs(nums, target, i, m - 1)
else
# 找到目标元素,返回其索引
return m
end
end
### 二分查找 ###
def binary_search(nums, target)
n = nums.length
# 求解问题 f(0, n-1)
dfs(nums, target, 0, n - 1)
end
### Driver Code ###
if __FILE__ == $0
target = 6
nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35]
# 二分查找(双闭区间)
index = binary_search(nums, target)
puts "目标元素 6 的索引 = #{index}"
end

View File

@ -0,0 +1,46 @@
=begin
File: build_tree.rb
Created Time: 2024-05-13
Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
=end
require_relative '../utils/tree_node'
require_relative '../utils/print_util'
### 构建二叉树:分治 ###
def dfs(preorder, inorder_map, i, l, r)
# 子树区间为空时终止
return if r - l < 0
# 初始化根节点
root = TreeNode.new(preorder[i])
# 查询 m ,从而划分左右子树
m = inorder_map[preorder[i]]
# 子问题:构建左子树
root.left = dfs(preorder, inorder_map, i + 1, l, m - 1)
# 子问题:构建右子树
root.right = dfs(preorder, inorder_map, i + 1 + m - l, m + 1, r)
# 返回根节点
root
end
### 构建二叉树 ###
def build_tree(preorder, inorder)
# 初始化哈希表,存储 inorder 元素到索引的映射
inorder_map = {}
inorder.each_with_index { |val, i| inorder_map[val] = i }
dfs(preorder, inorder_map, 0, 0, inorder.length - 1)
end
### Driver Code ###
if __FILE__ == $0
preorder = [3, 9, 2, 1, 7]
inorder = [9, 3, 1, 2, 7]
puts "前序遍历 = #{preorder}"
puts "中序遍历 = #{inorder}"
root = build_tree(preorder, inorder)
puts "构建的二叉树为:"
print_tree(root)
end

View File

@ -0,0 +1,55 @@
=begin
File: hanota.rb
Created Time: 2024-05-13
Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
=end
### 移动一个圆盘 ###
def move(src, tar)
# 从 src 顶部拿出一个圆盘
pan = src.pop
# 将圆盘放入 tar 顶部
tar << pan
end
### 求解汉诺塔问题 f(i) ###
def dfs(i, src, buf, tar)
# 若 src 只剩下一个圆盘,则直接将其移到 tar
if i == 1
move(src, tar)
return
end
# 子问题 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)
end
### 求解汉诺塔问题 ###
def solve_hanota(_A, _B, _C)
n = _A.length
# 将 A 顶部 n 个圆盘借助 B 移到 C
dfs(n, _A, _B, _C)
end
### Driver Code ###
if __FILE__ == $0
# 列表尾部是柱子顶部
A = [5, 4, 3, 2, 1]
B = []
C = []
puts "初始状态下:"
puts "A = #{A}"
puts "B = #{B}"
puts "C = #{C}"
solve_hanota(A, B, C)
puts "圆盘移动完成后:"
puts "A = #{A}"
puts "B = #{B}"
puts "C = #{C}"
end

View File

@ -0,0 +1,37 @@
=begin
File: climbing_stairs_backtrack.rb
Created Time: 2024-05-29
Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
=end
### 回溯 ###
def backtrack(choices, state, n, res)
# 当爬到第 n 阶时,方案数量加 1
res[0] += 1 if state == n
# 遍历所有选择
for choice in choices
# 剪枝:不允许越过第 n 阶
next if state + choice > n
# 尝试:做出选择,更新状态
backtrack(choices, state + choice, n, res)
end
# 回退
end
### 爬楼梯:回溯 ###
def climbing_stairs_backtrack(n)
choices = [1, 2] # 可选择向上爬 1 阶或 2 阶
state = 0 # 从第 0 阶开始爬
res = [0] # 使用 res[0] 记录方案数量
backtrack(choices, state, n, res)
res.first
end
### Driver Code ###
if __FILE__ == $0
n = 9
res = climbing_stairs_backtrack(n)
puts "#{n} 阶楼梯共有 #{res} 种方案"
end

View File

@ -0,0 +1,31 @@
=begin
File: climbing_stairs_constraint_dp.rb
Created Time: 2024-05-29
Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
=end
### 带约束爬楼梯:动态规划 ###
def climbing_stairs_constraint_dp(n)
return 1 if n == 1 || n == 2
# 初始化 dp 表,用于存储子问题的解
dp = Array.new(n + 1) { Array.new(3, 0) }
# 初始状态:预设最小子问题的解
dp[1][1], dp[1][2] = 1, 0
dp[2][1], dp[2][2] = 0, 1
# 状态转移:从较小子问题逐步求解较大子问题
for i in 3...(n + 1)
dp[i][1] = dp[i - 1][2]
dp[i][2] = dp[i - 2][1] + dp[i - 2][2]
end
dp[n][1] + dp[n][2]
end
### Driver Code ###
if __FILE__ == $0
n = 9
res = climbing_stairs_constraint_dp(n)
puts "#{n} 阶楼梯共有 #{res} 种方案"
end

Some files were not shown because too many files have changed in this diff Show More