mirror of
https://github.com/krahets/hello-algo.git
synced 2024-12-26 02:26:28 +08:00
build
This commit is contained in:
parent
edcd1e5c10
commit
d0670b87ac
9 changed files with 691 additions and 41 deletions
|
@ -8,7 +8,7 @@ comments: true
|
|||
|
||||
给定一个二叉树的前序遍历 `preorder` 和中序遍历 `inorder` ,请从中构建二叉树,返回二叉树的根节点。
|
||||
|
||||
![构建二叉树的示例数据](build_binary_tree.assets/build_tree_example.png)
|
||||
![构建二叉树的示例数据](build_binary_tree_problem.assets/build_tree_example.png)
|
||||
|
||||
<p align="center"> Fig. 构建二叉树的示例数据 </p>
|
||||
|
||||
|
@ -31,7 +31,7 @@ comments: true
|
|||
2. 查找根节点在 `inorder` 中的索引,基于该索引可将 `inorder` 划分为 `[ 9 | 3 | 1 2 7 ]` ;
|
||||
3. 根据 `inorder` 划分结果,可得左子树和右子树分别有 1 个和 3 个节点,从而可将 `preorder` 划分为 `[ 3 | 9 | 2 1 7 ]` ;
|
||||
|
||||
![在前序和中序遍历中划分子树](build_binary_tree.assets/build_tree_preorder_inorder_division.png)
|
||||
![在前序和中序遍历中划分子树](build_binary_tree_problem.assets/build_tree_preorder_inorder_division.png)
|
||||
|
||||
<p align="center"> Fig. 在前序和中序遍历中划分子树 </p>
|
||||
|
||||
|
@ -55,7 +55,7 @@ comments: true
|
|||
|
||||
请注意,右子树根节点索引中的 $(m-l)$ 的含义是“左子树的节点数量”,建议配合下图理解。
|
||||
|
||||
![根节点和左右子树的索引区间表示](build_binary_tree.assets/build_tree_division_pointers.png)
|
||||
![根节点和左右子树的索引区间表示](build_binary_tree_problem.assets/build_tree_division_pointers.png)
|
||||
|
||||
<p align="center"> Fig. 根节点和左右子树的索引区间表示 </p>
|
||||
|
||||
|
@ -88,7 +88,7 @@ comments: true
|
|||
l: int,
|
||||
r: int,
|
||||
) -> TreeNode | None:
|
||||
"""构建二叉树 DFS"""
|
||||
"""构建二叉树:分治"""
|
||||
# 子树区间为空时终止
|
||||
if r - l < 0:
|
||||
return None
|
||||
|
@ -96,9 +96,9 @@ comments: true
|
|||
root = TreeNode(preorder[i])
|
||||
# 查询 m ,从而划分左右子树
|
||||
m = hmap[preorder[i]]
|
||||
# 递归构建左子树
|
||||
# 子问题:构建左子树
|
||||
root.left = dfs(preorder, inorder, hmap, i + 1, l, m - 1)
|
||||
# 递归构建右子树
|
||||
# 子问题:构建右子树
|
||||
root.right = dfs(preorder, inorder, hmap, i + 1 + m - l, m + 1, r)
|
||||
# 返回根节点
|
||||
return root
|
||||
|
@ -178,34 +178,34 @@ comments: true
|
|||
下图展示了构建二叉树的递归过程,各个节点是在向下“递”的过程中建立的,而各条边是在向上“归”的过程中建立的。
|
||||
|
||||
=== "<1>"
|
||||
![built_tree_step1](build_binary_tree.assets/built_tree_step1.png)
|
||||
![构建二叉树的递归过程](build_binary_tree_problem.assets/built_tree_step1.png)
|
||||
|
||||
=== "<2>"
|
||||
![built_tree_step2](build_binary_tree.assets/built_tree_step2.png)
|
||||
![built_tree_step2](build_binary_tree_problem.assets/built_tree_step2.png)
|
||||
|
||||
=== "<3>"
|
||||
![built_tree_step3](build_binary_tree.assets/built_tree_step3.png)
|
||||
![built_tree_step3](build_binary_tree_problem.assets/built_tree_step3.png)
|
||||
|
||||
=== "<4>"
|
||||
![built_tree_step4](build_binary_tree.assets/built_tree_step4.png)
|
||||
![built_tree_step4](build_binary_tree_problem.assets/built_tree_step4.png)
|
||||
|
||||
=== "<5>"
|
||||
![built_tree_step5](build_binary_tree.assets/built_tree_step5.png)
|
||||
![built_tree_step5](build_binary_tree_problem.assets/built_tree_step5.png)
|
||||
|
||||
=== "<6>"
|
||||
![built_tree_step6](build_binary_tree.assets/built_tree_step6.png)
|
||||
![built_tree_step6](build_binary_tree_problem.assets/built_tree_step6.png)
|
||||
|
||||
=== "<7>"
|
||||
![built_tree_step7](build_binary_tree.assets/built_tree_step7.png)
|
||||
![built_tree_step7](build_binary_tree_problem.assets/built_tree_step7.png)
|
||||
|
||||
=== "<8>"
|
||||
![built_tree_step8](build_binary_tree.assets/built_tree_step8.png)
|
||||
![built_tree_step8](build_binary_tree_problem.assets/built_tree_step8.png)
|
||||
|
||||
=== "<9>"
|
||||
![built_tree_step9](build_binary_tree.assets/built_tree_step9.png)
|
||||
![built_tree_step9](build_binary_tree_problem.assets/built_tree_step9.png)
|
||||
|
||||
=== "<10>"
|
||||
![built_tree_step10](build_binary_tree.assets/built_tree_step10.png)
|
||||
![built_tree_step10](build_binary_tree_problem.assets/built_tree_step10.png)
|
||||
|
||||
设树的节点数量为 $n$ ,初始化每一个节点(执行一个递归函数 `dfs()` )使用 $O(1)$ 时间。**因此总体时间复杂度为 $O(n)$** 。
|
||||
|
|
@ -2,7 +2,7 @@
|
|||
comments: true
|
||||
---
|
||||
|
||||
# 12.1. 分治
|
||||
# 12.1. 分治算法
|
||||
|
||||
「分治 Divide and Conquer」,全称分而治之,是一种非常重要的算法策略。分治通常基于递归实现,包括“分”和“治”两部分,主要步骤如下:
|
||||
|
||||
|
|
225
chapter_divide_and_conquer/hanota_problem.md
Normal file
225
chapter_divide_and_conquer/hanota_problem.md
Normal file
|
@ -0,0 +1,225 @@
|
|||
---
|
||||
comments: true
|
||||
---
|
||||
|
||||
# 12.3. 汉诺塔问题
|
||||
|
||||
在归并排序和构建二叉树中,我们将原问题分解为两个规模为原问题一半的子问题。然而,对于即将介绍的汉诺塔问题,我们采用不同的分解策略。
|
||||
|
||||
!!! question
|
||||
|
||||
给定三根柱子,记为 `A` , `B` , `C` 。起始状态下,柱子 `A` 上套着 $n$ 个圆盘,它们从上到下按照从小到大的顺序排列。我们的任务是要把这 $n$ 个圆盘移到柱子 `C` 上,并保持它们的原有顺序不变。在移动圆盘的过程中,需要遵守以下规则:
|
||||
|
||||
1. 圆盘只能从一个柱子顶部拿出,从另一个柱子顶部放入;
|
||||
2. 每次只能移动一个圆盘;
|
||||
3. 小圆盘必须时刻位于大圆盘之上;
|
||||
|
||||
![汉诺塔问题示例](hanota_problem.assets/hanota_example.png)
|
||||
|
||||
<p align="center"> Fig. 汉诺塔问题示例 </p>
|
||||
|
||||
在本文中,**我们将规模为 $i$ 的汉诺塔问题记做 $f(i)$** 。例如 $f(3)$ 代表将 $3$ 个圆盘从 `A` 移动至 `C` 的汉诺塔问题。
|
||||
|
||||
先考虑最简单的情况:对于问题 $f(1)$ ,即当只有一个圆盘时,则将它直接从 `A` 移动至 `C` 即可。
|
||||
|
||||
=== "<1>"
|
||||
![规模为 1 问题的解](hanota_problem.assets/hanota_f1_step1.png)
|
||||
|
||||
=== "<2>"
|
||||
![hanota_f1_step2](hanota_problem.assets/hanota_f1_step2.png)
|
||||
|
||||
对于问题 $f(2)$ ,即当有两个圆盘时,**由于要时刻满足小圆盘在大圆盘之上,因此需要借助 `B` 来完成移动**,包括三步:
|
||||
|
||||
1. 先将上面的小圆盘从 `A` 移至 `B` ;
|
||||
2. 再将大圆盘从 `A` 移至 `C` ;
|
||||
3. 最后将小圆盘从 `B` 移至 `C` ;
|
||||
|
||||
如下图所示,对于小圆盘的移动,**我们称 `C` 为目标柱、`B` 为缓冲柱**。
|
||||
|
||||
=== "<1>"
|
||||
![规模为 2 问题的解](hanota_problem.assets/hanota_f2_step1.png)
|
||||
|
||||
=== "<2>"
|
||||
![hanota_f2_step2](hanota_problem.assets/hanota_f2_step2.png)
|
||||
|
||||
=== "<3>"
|
||||
![hanota_f2_step3](hanota_problem.assets/hanota_f2_step3.png)
|
||||
|
||||
=== "<4>"
|
||||
![hanota_f2_step4](hanota_problem.assets/hanota_f2_step4.png)
|
||||
|
||||
对于问题 $f(3)$ ,即当有三个圆盘时,情况变得稍微复杂了一些。由于已知 $f(1)$ 和 $f(2)$ 的解,我们可以从分治角度思考,**将 `A` 顶部的两个圆盘看做一个整体**,并执行以下步骤:
|
||||
|
||||
1. 令 `B` 为目标柱、`C` 为缓冲柱,将两个圆盘从 `A` 移动至 `B` ;
|
||||
2. 将 `A` 中剩余的一个圆盘从 `A` 移动至 `C` ;
|
||||
3. 令 `C` 为目标柱、`A` 为缓冲柱,将两个圆盘从 `B` 移动至 `C` ;
|
||||
|
||||
这样三个圆盘就被顺利地从 `A` 移动至 `C` 了。
|
||||
|
||||
=== "<1>"
|
||||
![规模为 3 问题的解](hanota_problem.assets/hanota_f3_step1.png)
|
||||
|
||||
=== "<2>"
|
||||
![hanota_f3_step2](hanota_problem.assets/hanota_f3_step2.png)
|
||||
|
||||
=== "<3>"
|
||||
![hanota_f3_step3](hanota_problem.assets/hanota_f3_step3.png)
|
||||
|
||||
=== "<4>"
|
||||
![hanota_f3_step4](hanota_problem.assets/hanota_f3_step4.png)
|
||||
|
||||
本质上看,我们将问题 $f(3)$ 划分为两个子问题 $f(2)$ 和子问题 $f(1)$。按顺序解决这三个子问题之后,原问题随之得到解决。**以上分析说明了子问题的独立性,以及解是可以合并的**。
|
||||
|
||||
至此,我们可总结出汉诺塔问题的分治策略:**将原问题 $f(n)$ 划分为两个子问题 $f(n-1)$ 和一个子问题 $f(1)$** 。子问题的解决顺序为:
|
||||
|
||||
1. 将 $n-1$ 个圆盘借助 `C` 从 `A` 移至 `B` ;
|
||||
2. 将剩余 $1$ 个圆盘从 `A` 直接移至 `C` ;
|
||||
3. 将 $n-1$ 个圆盘借助 `A` 从 `B` 移至 `C` ;
|
||||
|
||||
并且,对于这两个子问题 $f(n-1)$ ,**可以通过相同的方式进行递归划分**,直至达到最小子问题 $f(1)$ 。而 $f(1)$ 的解是已知的,只需一次移动操作即可。
|
||||
|
||||
![汉诺塔问题的分治策略](hanota_problem.assets/hanota_divide_and_conquer.png)
|
||||
|
||||
<p align="center"> Fig. 汉诺塔问题的分治策略 </p>
|
||||
|
||||
在代码实现中,我们声明一个递归函数 `dfs(i, src, buf, tar)` ,它的作用是将柱 `src` 顶部的 $i$ 个圆盘借助缓冲柱 `buf` 移动至目标柱 `tar` 。
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="hanota.java"
|
||||
[class]{hanota}-[func]{move}
|
||||
|
||||
[class]{hanota}-[func]{dfs}
|
||||
|
||||
[class]{hanota}-[func]{hanota}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="hanota.cpp"
|
||||
[class]{}-[func]{move}
|
||||
|
||||
[class]{}-[func]{dfs}
|
||||
|
||||
[class]{}-[func]{hanota}
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="hanota.py"
|
||||
def move(src: list[int], tar: list[int]):
|
||||
"""移动一个圆盘"""
|
||||
# 从 src 顶部拿出一个圆盘
|
||||
pan = src.pop()
|
||||
# 将圆盘放入 tar 顶部
|
||||
tar.append(pan)
|
||||
|
||||
def dfs(i: int, src: list[int], buf: list[int], tar: list[int]):
|
||||
"""求解汉诺塔:问题 f(i)"""
|
||||
# 若 src 只剩下一个圆盘,则直接将其移到 tar
|
||||
if i == 1:
|
||||
move(src, tar)
|
||||
return
|
||||
# 子问题 f(i-1) :将 src 顶部 i-1 个圆盘借助 tar 移到 buf
|
||||
dfs(i - 1, src, tar, buf)
|
||||
# 子问题 f(1) :将 src 剩余一个圆盘移到 tar
|
||||
move(src, tar)
|
||||
# 子问题 f(i-1) :将 buf 顶部 i-1 个圆盘借助 src 移到 tar
|
||||
dfs(i - 1, buf, src, tar)
|
||||
|
||||
def hanota(A: list[int], B: list[int], C: list[int]):
|
||||
"""求解汉诺塔"""
|
||||
n = len(A)
|
||||
# 将 A 顶部 n 个圆盘借助 B 移到 C
|
||||
dfs(n, A, B, C)
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="hanota.go"
|
||||
[class]{}-[func]{move}
|
||||
|
||||
[class]{}-[func]{dfs}
|
||||
|
||||
[class]{}-[func]{hanota}
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```javascript title="hanota.js"
|
||||
[class]{}-[func]{move}
|
||||
|
||||
[class]{}-[func]{dfs}
|
||||
|
||||
[class]{}-[func]{hanota}
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="hanota.ts"
|
||||
[class]{}-[func]{move}
|
||||
|
||||
[class]{}-[func]{dfs}
|
||||
|
||||
[class]{}-[func]{hanota}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="hanota.c"
|
||||
[class]{}-[func]{move}
|
||||
|
||||
[class]{}-[func]{dfs}
|
||||
|
||||
[class]{}-[func]{hanota}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="hanota.cs"
|
||||
[class]{hanota}-[func]{move}
|
||||
|
||||
[class]{hanota}-[func]{dfs}
|
||||
|
||||
[class]{hanota}-[func]{hanota}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="hanota.swift"
|
||||
[class]{}-[func]{move}
|
||||
|
||||
[class]{}-[func]{dfs}
|
||||
|
||||
[class]{}-[func]{hanota}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="hanota.zig"
|
||||
[class]{}-[func]{move}
|
||||
|
||||
[class]{}-[func]{dfs}
|
||||
|
||||
[class]{}-[func]{hanota}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="hanota.dart"
|
||||
[class]{}-[func]{move}
|
||||
|
||||
[class]{}-[func]{dfs}
|
||||
|
||||
[class]{}-[func]{hanota}
|
||||
```
|
||||
|
||||
如下图所示,汉诺塔问题形成一个高度为 $n$ 的递归树,每个节点代表一个子问题、对应一个开启的 `dfs()` 函数,**因此时间复杂度为 $O(2^n)$ ,空间复杂度为 $O(n)$** 。
|
||||
|
||||
![汉诺塔问题的递归树](hanota_problem.assets/hanota_recursive_tree.png)
|
||||
|
||||
<p align="center"> Fig. 汉诺塔问题的递归树 </p>
|
||||
|
||||
有趣的是,汉诺塔问题源自一种古老的传说故事。在古印度的一个寺庙里,僧侣们有三根高大的钻石柱子,以及 $64$ 个大小不一的金圆盘。僧侣们不断地移动原盘,他们相信在最后一个圆盘被正确放置的那一刻,这个世界就会结束。
|
||||
|
||||
然而根据以上分析,即使僧侣们每秒钟移动一次,总共需要大约 $2^{64} \approx 1.84×10^{19}$ 秒,合约 $5850$ 亿年,远远超过了现在对宇宙年龄的估计。所以,倘若这个传说是真的,我们应该不需要担心世界末日的到来。
|
|
@ -148,7 +148,23 @@ $$
|
|||
=== "Zig"
|
||||
|
||||
```zig title="min_cost_climbing_stairs_dp.zig"
|
||||
[class]{}-[func]{minCostClimbingStairsDP}
|
||||
// 爬楼梯最小代价:动态规划
|
||||
fn minCostClimbingStairsDP(comptime cost: []i32) i32 {
|
||||
comptime var n = cost.len - 1;
|
||||
if (n == 1 or n == 2) {
|
||||
return cost[n];
|
||||
}
|
||||
// 初始化 dp 表,用于存储子问题的解
|
||||
var dp = [_]i32{-1} ** (n + 1);
|
||||
// 初始状态:预设最小子问题的解
|
||||
dp[1] = cost[1];
|
||||
dp[2] = cost[2];
|
||||
// 状态转移:从较小子问题逐步求解较大子问题
|
||||
for (3..n + 1) |i| {
|
||||
dp[i] = @min(dp[i - 1], dp[i - 2]) + cost[i];
|
||||
}
|
||||
return dp[n];
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
@ -264,7 +280,22 @@ $$
|
|||
=== "Zig"
|
||||
|
||||
```zig title="min_cost_climbing_stairs_dp.zig"
|
||||
[class]{}-[func]{minCostClimbingStairsDPComp}
|
||||
// 爬楼梯最小代价:状态压缩后的动态规划
|
||||
fn minCostClimbingStairsDPComp(cost: []i32) i32 {
|
||||
var n = cost.len - 1;
|
||||
if (n == 1 or n == 2) {
|
||||
return cost[n];
|
||||
}
|
||||
var a = cost[1];
|
||||
var b = cost[2];
|
||||
// 状态转移:从较小子问题逐步求解较大子问题
|
||||
for (3..n + 1) |i| {
|
||||
var tmp = b;
|
||||
b = @min(a, tmp) + cost[i];
|
||||
a = tmp;
|
||||
}
|
||||
return b;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
@ -439,7 +470,25 @@ $$
|
|||
=== "Zig"
|
||||
|
||||
```zig title="climbing_stairs_constraint_dp.zig"
|
||||
[class]{}-[func]{climbingStairsConstraintDP}
|
||||
// 带约束爬楼梯:动态规划
|
||||
fn climbingStairsConstraintDP(comptime n: usize) i32 {
|
||||
if (n == 1 or n == 2) {
|
||||
return @intCast(n);
|
||||
}
|
||||
// 初始化 dp 表,用于存储子问题的解
|
||||
var dp = [_][3]i32{ [_]i32{ -1, -1, -1 } } ** (n + 1);
|
||||
// 初始状态:预设最小子问题的解
|
||||
dp[1][1] = 1;
|
||||
dp[1][2] = 0;
|
||||
dp[2][1] = 0;
|
||||
dp[2][2] = 1;
|
||||
// 状态转移:从较小子问题逐步求解较大子问题
|
||||
for (3..n + 1) |i| {
|
||||
dp[i][1] = dp[i - 1][2];
|
||||
dp[i][2] = dp[i - 2][1] + dp[i - 2][2];
|
||||
}
|
||||
return dp[n][1] + dp[n][2];
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
|
|
@ -221,7 +221,22 @@ $$
|
|||
=== "Zig"
|
||||
|
||||
```zig title="min_path_sum.zig"
|
||||
[class]{}-[func]{minPathSumDFS}
|
||||
// 最小路径和:暴力搜索
|
||||
fn minPathSumDFS(grid: anytype, i: i32, j: i32) i32 {
|
||||
// 若为左上角单元格,则终止搜索
|
||||
if (i == 0 and j == 0) {
|
||||
return grid[0][0];
|
||||
}
|
||||
// 若行列索引越界,则返回 +∞ 代价
|
||||
if (i < 0 or j < 0) {
|
||||
return std.math.maxInt(i32);
|
||||
}
|
||||
// 计算从左上角到 (i-1, j) 和 (i, j-1) 的最小路径代价
|
||||
var left = minPathSumDFS(grid, i - 1, j);
|
||||
var up = minPathSumDFS(grid, i, j - 1);
|
||||
// 返回从左上角到 (i, j) 的最小路径代价
|
||||
return @min(left, up) + grid[@as(usize, @intCast(i))][@as(usize, @intCast(j))];
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
@ -379,7 +394,28 @@ $$
|
|||
=== "Zig"
|
||||
|
||||
```zig title="min_path_sum.zig"
|
||||
[class]{}-[func]{minPathSumDFSMem}
|
||||
// 最小路径和:记忆化搜索
|
||||
fn minPathSumDFSMem(grid: anytype, mem: anytype, i: i32, j: i32) i32 {
|
||||
// 若为左上角单元格,则终止搜索
|
||||
if (i == 0 and j == 0) {
|
||||
return grid[0][0];
|
||||
}
|
||||
// 若行列索引越界,则返回 +∞ 代价
|
||||
if (i < 0 or j < 0) {
|
||||
return std.math.maxInt(i32);
|
||||
}
|
||||
// 若已有记录,则直接返回
|
||||
if (mem[@as(usize, @intCast(i))][@as(usize, @intCast(j))] != -1) {
|
||||
return mem[@as(usize, @intCast(i))][@as(usize, @intCast(j))];
|
||||
}
|
||||
// 计算从左上角到 (i-1, j) 和 (i, j-1) 的最小路径代价
|
||||
var left = minPathSumDFSMem(grid, mem, i - 1, j);
|
||||
var up = minPathSumDFSMem(grid, mem, i, j - 1);
|
||||
// 返回从左上角到 (i, j) 的最小路径代价
|
||||
// 记录并返回左上角到 (i, j) 的最小路径代价
|
||||
mem[@as(usize, @intCast(i))][@as(usize, @intCast(j))] = @min(left, up) + grid[@as(usize, @intCast(i))][@as(usize, @intCast(j))];
|
||||
return mem[@as(usize, @intCast(i))][@as(usize, @intCast(j))];
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
@ -534,7 +570,29 @@ $$
|
|||
=== "Zig"
|
||||
|
||||
```zig title="min_path_sum.zig"
|
||||
[class]{}-[func]{minPathSumDP}
|
||||
// 最小路径和:动态规划
|
||||
fn minPathSumDP(comptime grid: anytype) i32 {
|
||||
comptime var n = grid.len;
|
||||
comptime var m = grid[0].len;
|
||||
// 初始化 dp 表
|
||||
var dp = [_][m]i32{[_]i32{0} ** m} ** n;
|
||||
dp[0][0] = grid[0][0];
|
||||
// 状态转移:首行
|
||||
for (1..m) |j| {
|
||||
dp[0][j] = dp[0][j - 1] + grid[0][j];
|
||||
}
|
||||
// 状态转移:首列
|
||||
for (1..n) |i| {
|
||||
dp[i][0] = dp[i - 1][0] + grid[i][0];
|
||||
}
|
||||
// 状态转移:其余行列
|
||||
for (1..n) |i| {
|
||||
for (1..m) |j| {
|
||||
dp[i][j] = @min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j];
|
||||
}
|
||||
}
|
||||
return dp[n - 1][m - 1];
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
@ -718,7 +776,27 @@ $$
|
|||
=== "Zig"
|
||||
|
||||
```zig title="min_path_sum.zig"
|
||||
[class]{}-[func]{minPathSumDPComp}
|
||||
// 最小路径和:状态压缩后的动态规划
|
||||
fn minPathSumDPComp(comptime grid: anytype) i32 {
|
||||
comptime var n = grid.len;
|
||||
comptime var m = grid[0].len;
|
||||
// 初始化 dp 表
|
||||
var dp = [_]i32{0} ** m;
|
||||
// 状态转移:首行
|
||||
dp[0] = grid[0][0];
|
||||
for (1..m) |j| {
|
||||
dp[j] = dp[j - 1] + grid[0][j];
|
||||
}
|
||||
// 状态转移:其余行
|
||||
for (1..n) |i| {
|
||||
// 状态转移:首列
|
||||
dp[0] = dp[0] + grid[i][0];
|
||||
for (1..m) |j| {
|
||||
dp[j] = @min(dp[j - 1], dp[j]) + grid[i][j];
|
||||
}
|
||||
}
|
||||
return dp[m - 1];
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
|
|
@ -218,7 +218,32 @@ $$
|
|||
=== "Zig"
|
||||
|
||||
```zig title="edit_distance.zig"
|
||||
[class]{}-[func]{editDistanceDP}
|
||||
// 编辑距离:动态规划
|
||||
fn editDistanceDP(comptime s: []const u8, comptime t: []const u8) i32 {
|
||||
comptime var n = s.len;
|
||||
comptime var m = t.len;
|
||||
var dp = [_][m + 1]i32{[_]i32{0} ** (m + 1)} ** (n + 1);
|
||||
// 状态转移:首行首列
|
||||
for (1..n + 1) |i| {
|
||||
dp[i][0] = @intCast(i);
|
||||
}
|
||||
for (1..m + 1) |j| {
|
||||
dp[0][j] = @intCast(j);
|
||||
}
|
||||
// 状态转移:其余行列
|
||||
for (1..n + 1) |i| {
|
||||
for (1..m + 1) |j| {
|
||||
if (s[i - 1] == t[j - 1]) {
|
||||
// 若两字符相等,则直接跳过此两字符
|
||||
dp[i][j] = dp[i - 1][j - 1];
|
||||
} else {
|
||||
// 最少编辑步数 = 插入、删除、替换这三种操作的最少编辑步数 + 1
|
||||
dp[i][j] = @min(@min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][m];
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
@ -438,7 +463,35 @@ $$
|
|||
=== "Zig"
|
||||
|
||||
```zig title="edit_distance.zig"
|
||||
[class]{}-[func]{editDistanceDPComp}
|
||||
// 编辑距离:状态压缩后的动态规划
|
||||
fn editDistanceDPComp(comptime s: []const u8, comptime t: []const u8) i32 {
|
||||
comptime var n = s.len;
|
||||
comptime var m = t.len;
|
||||
var dp = [_]i32{0} ** (m + 1);
|
||||
// 状态转移:首行
|
||||
for (1..m + 1) |j| {
|
||||
dp[j] = @intCast(j);
|
||||
}
|
||||
// 状态转移:其余行
|
||||
for (1..n + 1) |i| {
|
||||
// 状态转移:首列
|
||||
var leftup = dp[0]; // 暂存 dp[i-1, j-1]
|
||||
dp[0] = @intCast(i);
|
||||
// 状态转移:其余列
|
||||
for (1..m + 1) |j| {
|
||||
var temp = dp[j];
|
||||
if (s[i - 1] == t[j - 1]) {
|
||||
// 若两字符相等,则直接跳过此两字符
|
||||
dp[j] = leftup;
|
||||
} else {
|
||||
// 最少编辑步数 = 插入、删除、替换这三种操作的最少编辑步数 + 1
|
||||
dp[j] = @min(@min(dp[j - 1], dp[j]), leftup) + 1;
|
||||
}
|
||||
leftup = temp; // 更新为下一轮的 dp[i-1, j-1]
|
||||
}
|
||||
}
|
||||
return dp[m];
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
|
|
@ -195,7 +195,16 @@ comments: true
|
|||
}
|
||||
}
|
||||
|
||||
[class]{}-[func]{climbingStairsBacktrack}
|
||||
// 爬楼梯:回溯
|
||||
fn climbingStairsBacktrack(n: usize) !i32 {
|
||||
var choices = [_]i32{ 1, 2 }; // 可选择向上爬 1 或 2 阶
|
||||
var state: i32 = 0; // 从第 0 阶开始爬
|
||||
var res = std.ArrayList(i32).init(std.heap.page_allocator);
|
||||
defer res.deinit();
|
||||
try res.append(0); // 使用 res[0] 记录方案数量
|
||||
backtrack(&choices, state, @intCast(n), res);
|
||||
return res.items[0];
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
@ -362,7 +371,10 @@ $$
|
|||
return count;
|
||||
}
|
||||
|
||||
[class]{}-[func]{climbingStairsDFS}
|
||||
// 爬楼梯:搜索
|
||||
fn climbingStairsDFS(comptime n: usize) i32 {
|
||||
return dfs(n);
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
@ -552,7 +564,12 @@ $$
|
|||
return count;
|
||||
}
|
||||
|
||||
[class]{}-[func]{climbingStairsDFSMem}
|
||||
// 爬楼梯:记忆化搜索
|
||||
fn climbingStairsDFSMem(comptime n: usize) i32 {
|
||||
// mem[i] 记录爬到第 i 阶的方案总数,-1 代表无记录
|
||||
var mem = [_]i32{ -1 } ** (n + 1);
|
||||
return dfs(n, &mem);
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
@ -687,7 +704,23 @@ $$
|
|||
=== "Zig"
|
||||
|
||||
```zig title="climbing_stairs_dp.zig"
|
||||
[class]{}-[func]{climbingStairsDP}
|
||||
// 爬楼梯:动态规划
|
||||
fn climbingStairsDP(comptime n: usize) i32 {
|
||||
// 已知 dp[1] 和 dp[2] ,返回之
|
||||
if (n == 1 or n == 2) {
|
||||
return @intCast(n);
|
||||
}
|
||||
// 初始化 dp 表,用于存储子问题的解
|
||||
var dp = [_]i32{-1} ** (n + 1);
|
||||
// 初始状态:预设最小子问题的解
|
||||
dp[1] = 1;
|
||||
dp[2] = 2;
|
||||
// 状态转移:从较小子问题逐步求解较大子问题
|
||||
for (3..n + 1) |i| {
|
||||
dp[i] = dp[i - 1] + dp[i - 2];
|
||||
}
|
||||
return dp[n];
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
@ -805,7 +838,20 @@ $$
|
|||
=== "Zig"
|
||||
|
||||
```zig title="climbing_stairs_dp.zig"
|
||||
[class]{}-[func]{climbingStairsDPComp}
|
||||
// 爬楼梯:状态压缩后的动态规划
|
||||
fn climbingStairsDPComp(comptime n: usize) i32 {
|
||||
if (n == 1 or n == 2) {
|
||||
return @intCast(n);
|
||||
}
|
||||
var a: i32 = 1;
|
||||
var b: i32 = 2;
|
||||
for (3..n + 1) |_| {
|
||||
var tmp = b;
|
||||
b = a + b;
|
||||
a = tmp;
|
||||
}
|
||||
return b;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
|
|
@ -177,7 +177,22 @@ $$
|
|||
=== "Zig"
|
||||
|
||||
```zig title="knapsack.zig"
|
||||
[class]{}-[func]{knapsackDFS}
|
||||
// 0-1 背包:暴力搜索
|
||||
fn knapsackDFS(wgt: []i32, val: []i32, i: usize, c: usize) i32 {
|
||||
// 若已选完所有物品或背包无容量,则返回价值 0
|
||||
if (i == 0 or c == 0) {
|
||||
return 0;
|
||||
}
|
||||
// 若超过背包容量,则只能不放入背包
|
||||
if (wgt[i - 1] > c) {
|
||||
return knapsackDFS(wgt, val, i - 1, c);
|
||||
}
|
||||
// 计算不放入和放入物品 i 的最大价值
|
||||
var no = knapsackDFS(wgt, val, i - 1, c);
|
||||
var yes = knapsackDFS(wgt, val, i - 1, c - @as(usize, @intCast(wgt[i - 1]))) + val[i - 1];
|
||||
// 返回两种方案中价值更大的那一个
|
||||
return @max(no, yes);
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
@ -333,7 +348,27 @@ $$
|
|||
=== "Zig"
|
||||
|
||||
```zig title="knapsack.zig"
|
||||
[class]{}-[func]{knapsackDFSMem}
|
||||
// 0-1 背包:记忆化搜索
|
||||
fn knapsackDFSMem(wgt: []i32, val: []i32, mem: anytype, i: usize, c: usize) i32 {
|
||||
// 若已选完所有物品或背包无容量,则返回价值 0
|
||||
if (i == 0 or c == 0) {
|
||||
return 0;
|
||||
}
|
||||
// 若已有记录,则直接返回
|
||||
if (mem[i][c] != -1) {
|
||||
return mem[i][c];
|
||||
}
|
||||
// 若超过背包容量,则只能不放入背包
|
||||
if (wgt[i - 1] > c) {
|
||||
return knapsackDFSMem(wgt, val, mem, i - 1, c);
|
||||
}
|
||||
// 计算不放入和放入物品 i 的最大价值
|
||||
var no = knapsackDFSMem(wgt, val, mem, i - 1, c);
|
||||
var yes = knapsackDFSMem(wgt, val, mem, i - 1, c - @as(usize, @intCast(wgt[i - 1]))) + val[i - 1];
|
||||
// 记录并返回两种方案中价值更大的那一个
|
||||
mem[i][c] = @max(no, yes);
|
||||
return mem[i][c];
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
@ -477,7 +512,25 @@ $$
|
|||
=== "Zig"
|
||||
|
||||
```zig title="knapsack.zig"
|
||||
[class]{}-[func]{knapsackDP}
|
||||
// 0-1 背包:动态规划
|
||||
fn knapsackDP(comptime wgt: []i32, val: []i32, comptime cap: usize) i32 {
|
||||
comptime var n = wgt.len;
|
||||
// 初始化 dp 表
|
||||
var dp = [_][cap + 1]i32{[_]i32{0} ** (cap + 1)} ** (n + 1);
|
||||
// 状态转移
|
||||
for (1..n + 1) |i| {
|
||||
for (1..cap + 1) |c| {
|
||||
if (wgt[i - 1] > c) {
|
||||
// 若超过背包容量,则不选物品 i
|
||||
dp[i][c] = dp[i - 1][c];
|
||||
} else {
|
||||
// 不选和选物品 i 这两种方案的较大值
|
||||
dp[i][c] = @max(dp[i - 1][c], dp[i - 1][c - @as(usize, @intCast(wgt[i - 1]))] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][cap];
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
@ -679,7 +732,24 @@ $$
|
|||
=== "Zig"
|
||||
|
||||
```zig title="knapsack.zig"
|
||||
[class]{}-[func]{knapsackDPComp}
|
||||
// 0-1 背包:状态压缩后的动态规划
|
||||
fn knapsackDPComp(wgt: []i32, val: []i32, comptime cap: usize) i32 {
|
||||
var n = wgt.len;
|
||||
// 初始化 dp 表
|
||||
var dp = [_]i32{0} ** (cap + 1);
|
||||
// 状态转移
|
||||
for (1..n + 1) |i| {
|
||||
// 倒序遍历
|
||||
var c = cap;
|
||||
while (c > 0) : (c -= 1) {
|
||||
if (wgt[i - 1] < c) {
|
||||
// 不选和选物品 i 这两种方案的较大值
|
||||
dp[c] = @max(dp[c], dp[c - @as(usize, @intCast(wgt[i - 1]))] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[cap];
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
|
|
@ -159,7 +159,25 @@ $$
|
|||
=== "Zig"
|
||||
|
||||
```zig title="unbounded_knapsack.zig"
|
||||
[class]{}-[func]{unboundedKnapsackDP}
|
||||
// 完全背包:动态规划
|
||||
fn unboundedKnapsackDP(comptime wgt: []i32, val: []i32, comptime cap: usize) i32 {
|
||||
comptime var n = wgt.len;
|
||||
// 初始化 dp 表
|
||||
var dp = [_][cap + 1]i32{[_]i32{0} ** (cap + 1)} ** (n + 1);
|
||||
// 状态转移
|
||||
for (1..n + 1) |i| {
|
||||
for (1..cap + 1) |c| {
|
||||
if (wgt[i - 1] > c) {
|
||||
// 若超过背包容量,则不选物品 i
|
||||
dp[i][c] = dp[i - 1][c];
|
||||
} else {
|
||||
// 不选和选物品 i 这两种方案的较大值
|
||||
dp[i][c] = @max(dp[i - 1][c], dp[i][c - @as(usize, @intCast(wgt[i - 1]))] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][cap];
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
@ -316,7 +334,25 @@ $$
|
|||
=== "Zig"
|
||||
|
||||
```zig title="unbounded_knapsack.zig"
|
||||
[class]{}-[func]{unboundedKnapsackDPComp}
|
||||
// 完全背包:状态压缩后的动态规划
|
||||
fn unboundedKnapsackDPComp(comptime wgt: []i32, val: []i32, comptime cap: usize) i32 {
|
||||
comptime var n = wgt.len;
|
||||
// 初始化 dp 表
|
||||
var dp = [_]i32{0} ** (cap + 1);
|
||||
// 状态转移
|
||||
for (1..n + 1) |i| {
|
||||
for (1..cap + 1) |c| {
|
||||
if (wgt[i - 1] > c) {
|
||||
// 若超过背包容量,则不选物品 i
|
||||
dp[c] = dp[c];
|
||||
} else {
|
||||
// 不选和选物品 i 这两种方案的较大值
|
||||
dp[c] = @max(dp[c], dp[c - @as(usize, @intCast(wgt[i - 1]))] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[cap];
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
@ -516,7 +552,34 @@ $$
|
|||
=== "Zig"
|
||||
|
||||
```zig title="coin_change.zig"
|
||||
[class]{}-[func]{coinChangeDP}
|
||||
// 零钱兑换:动态规划
|
||||
fn coinChangeDP(comptime coins: []i32, comptime amt: usize) i32 {
|
||||
comptime var n = coins.len;
|
||||
comptime var max = amt + 1;
|
||||
// 初始化 dp 表
|
||||
var dp = [_][amt + 1]i32{[_]i32{0} ** (amt + 1)} ** (n + 1);
|
||||
// 状态转移:首行首列
|
||||
for (1..amt + 1) |a| {
|
||||
dp[0][a] = max;
|
||||
}
|
||||
// 状态转移:其余行列
|
||||
for (1..n + 1) |i| {
|
||||
for (1..amt + 1) |a| {
|
||||
if (coins[i - 1] > @as(i32, @intCast(a))) {
|
||||
// 若超过背包容量,则不选硬币 i
|
||||
dp[i][a] = dp[i - 1][a];
|
||||
} else {
|
||||
// 不选和选硬币 i 这两种方案的较小值
|
||||
dp[i][a] = @min(dp[i - 1][a], dp[i][a - @as(usize, @intCast(coins[i - 1]))] + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (dp[n][amt] != max) {
|
||||
return @intCast(dp[n][amt]);
|
||||
} else {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
@ -710,7 +773,32 @@ $$
|
|||
=== "Zig"
|
||||
|
||||
```zig title="coin_change.zig"
|
||||
[class]{}-[func]{coinChangeDPComp}
|
||||
// 零钱兑换:状态压缩后的动态规划
|
||||
fn coinChangeDPComp(comptime coins: []i32, comptime amt: usize) i32 {
|
||||
comptime var n = coins.len;
|
||||
comptime var max = amt + 1;
|
||||
// 初始化 dp 表
|
||||
var dp = [_]i32{0} ** (amt + 1);
|
||||
@memset(&dp, max);
|
||||
dp[0] = 0;
|
||||
// 状态转移
|
||||
for (1..n + 1) |i| {
|
||||
for (1..amt + 1) |a| {
|
||||
if (coins[i - 1] > @as(i32, @intCast(a))) {
|
||||
// 若超过背包容量,则不选硬币 i
|
||||
dp[a] = dp[a];
|
||||
} else {
|
||||
// 不选和选硬币 i 这两种方案的较小值
|
||||
dp[a] = @min(dp[a], dp[a - @as(usize, @intCast(coins[i - 1]))] + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (dp[amt] != max) {
|
||||
return @intCast(dp[amt]);
|
||||
} else {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
@ -879,7 +967,29 @@ $$
|
|||
=== "Zig"
|
||||
|
||||
```zig title="coin_change_ii.zig"
|
||||
[class]{}-[func]{coinChangeIIDP}
|
||||
// 零钱兑换 II:动态规划
|
||||
fn coinChangeIIDP(comptime coins: []i32, comptime amt: usize) i32 {
|
||||
comptime var n = coins.len;
|
||||
// 初始化 dp 表
|
||||
var dp = [_][amt + 1]i32{[_]i32{0} ** (amt + 1)} ** (n + 1);
|
||||
// 初始化首列
|
||||
for (0..n + 1) |i| {
|
||||
dp[i][0] = 1;
|
||||
}
|
||||
// 状态转移
|
||||
for (1..n + 1) |i| {
|
||||
for (1..amt + 1) |a| {
|
||||
if (coins[i - 1] > @as(i32, @intCast(a))) {
|
||||
// 若超过背包容量,则不选硬币 i
|
||||
dp[i][a] = dp[i - 1][a];
|
||||
} else {
|
||||
// 不选和选硬币 i 这两种方案的较小值
|
||||
dp[i][a] = dp[i - 1][a] + dp[i][a - @as(usize, @intCast(coins[i - 1]))];
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][amt];
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
@ -1020,7 +1130,26 @@ $$
|
|||
=== "Zig"
|
||||
|
||||
```zig title="coin_change_ii.zig"
|
||||
[class]{}-[func]{coinChangeIIDPComp}
|
||||
// 零钱兑换 II:状态压缩后的动态规划
|
||||
fn coinChangeIIDPComp(comptime coins: []i32, comptime amt: usize) i32 {
|
||||
comptime var n = coins.len;
|
||||
// 初始化 dp 表
|
||||
var dp = [_]i32{0} ** (amt + 1);
|
||||
dp[0] = 1;
|
||||
// 状态转移
|
||||
for (1..n + 1) |i| {
|
||||
for (1..amt + 1) |a| {
|
||||
if (coins[i - 1] > @as(i32, @intCast(a))) {
|
||||
// 若超过背包容量,则不选硬币 i
|
||||
dp[a] = dp[a];
|
||||
} else {
|
||||
// 不选和选硬币 i 这两种方案的较小值
|
||||
dp[a] = dp[a] + dp[a - @as(usize, @intCast(coins[i - 1]))];
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[amt];
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
|
Loading…
Reference in a new issue