diff --git a/chapter_dynamic_programming/dp_problem_features.md b/chapter_dynamic_programming/dp_problem_features.md index 068b18a62..0b7f08654 100644 --- a/chapter_dynamic_programming/dp_problem_features.md +++ b/chapter_dynamic_programming/dp_problem_features.md @@ -104,7 +104,23 @@ $$ === "Go" ```go title="min_cost_climbing_stairs_dp.go" - [class]{}-[func]{minCostClimbingStairsDP} + /* 爬楼梯最小代价:动态规划 */ + func minCostClimbingStairsDP(cost []int) int { + n := len(cost) - 1 + if n == 1 || n == 2 { + return cost[n] + } + // 初始化 dp 表,用于存储子问题的解 + dp := make([]int, n+1) + // 初始状态:预设最小子问题的解 + dp[1] = cost[1] + dp[2] = cost[2] + // 状态转移:从较小子问题逐步求解较大子问题 + for i := 3; i <= n; i++ { + dp[i] = int(math.Min(float64(dp[i-1]), float64(dp[i-2]+cost[i]))) + } + return dp[n] + } ``` === "JavaScript" @@ -255,7 +271,22 @@ $$ === "Go" ```go title="min_cost_climbing_stairs_dp.go" - [class]{}-[func]{minCostClimbingStairsDPComp} + /* 爬楼梯最小代价:状态压缩后的动态规划 */ + func minCostClimbingStairsDPComp(cost []int) int { + n := len(cost) - 1 + if n == 1 || n == 2 { + return cost[n] + } + // 初始状态:预设最小子问题的解 + a, b := cost[1], cost[2] + // 状态转移:从较小子问题逐步求解较大子问题 + for i := 3; i <= n; i++ { + tmp := b + b = int(math.Min(float64(a), float64(tmp+cost[i]))) + a = tmp + } + return b + } ``` === "JavaScript" @@ -450,7 +481,25 @@ $$ === "Go" ```go title="climbing_stairs_constraint_dp.go" - [class]{}-[func]{climbingStairsConstraintDP} + /* 带约束爬楼梯:动态规划 */ + func climbingStairsConstraintDP(n int) int { + if n == 1 || n == 2 { + return n + } + // 初始化 dp 表,用于存储子问题的解 + dp := make([][3]int, n+1) + // 初始状态:预设最小子问题的解 + dp[1][1] = 1 + dp[1][2] = 0 + dp[2][1] = 0 + dp[2][2] = 1 + // 状态转移:从较小子问题逐步求解较大子问题 + for i := 3; i <= n; i++ { + dp[i][1] = dp[i-1][2] + dp[i][2] = dp[i-2][1] + dp[i-2][2] + } + return dp[n][1] + dp[n][2] + } ``` === "JavaScript" diff --git a/chapter_dynamic_programming/dp_solution_pipeline.md b/chapter_dynamic_programming/dp_solution_pipeline.md index d7ad3a7e8..99802f36a 100644 --- a/chapter_dynamic_programming/dp_solution_pipeline.md +++ b/chapter_dynamic_programming/dp_solution_pipeline.md @@ -171,7 +171,22 @@ $$ === "Go" ```go title="min_path_sum.go" - [class]{}-[func]{minPathSumDFS} + /* 最小路径和:暴力搜索 */ + func minPathSumDFS(grid [][]int, i, j int) int { + // 若为左上角单元格,则终止搜索 + if i == 0 && j == 0 { + return grid[0][0] + } + // 若行列索引越界,则返回 +∞ 代价 + if i < 0 || j < 0 { + return math.MaxInt + } + // 计算从左上角到 (i-1, j) 和 (i, j-1) 的最小路径代价 + left := minPathSumDFS(grid, i-1, j) + up := minPathSumDFS(grid, i, j-1) + // 返回从左上角到 (i, j) 的最小路径代价 + return int(math.Min(float64(left), float64(up))) + grid[i][j] + } ``` === "JavaScript" @@ -354,7 +369,27 @@ $$ === "Go" ```go title="min_path_sum.go" - [class]{}-[func]{minPathSumDFSMem} + /* 最小路径和:记忆化搜索 */ + func minPathSumDFSMem(grid, mem [][]int, i, j int) int { + // 若为左上角单元格,则终止搜索 + if i == 0 && j == 0 { + return grid[0][0] + } + // 若行列索引越界,则返回 +∞ 代价 + if i < 0 || j < 0 { + return math.MaxInt + } + // 若已有记录,则直接返回 + if mem[i][j] != -1 { + return mem[i][j] + } + // 左边和上边单元格的最小路径代价 + left := minPathSumDFSMem(grid, mem, i-1, j) + up := minPathSumDFSMem(grid, mem, i, j-1) + // 记录并返回左上角到 (i, j) 的最小路径代价 + mem[i][j] = int(math.Min(float64(left), float64(up))) + grid[i][j] + return mem[i][j] + } ``` === "JavaScript" @@ -549,7 +584,31 @@ $$ === "Go" ```go title="min_path_sum.go" - [class]{}-[func]{minPathSumDP} + /* 最小路径和:动态规划 */ + func minPathSumDP(grid [][]int) int { + n, m := len(grid), len(grid[0]) + // 初始化 dp 表 + dp := make([][]int, n) + for i := 0; i < n; i++ { + dp[i] = make([]int, m) + } + dp[0][0] = grid[0][0] + // 状态转移:首行 + for j := 1; j < m; j++ { + dp[0][j] = dp[0][j-1] + grid[0][j] + } + // 状态转移:首列 + for i := 1; i < n; i++ { + dp[i][0] = dp[i-1][0] + grid[i][0] + } + // 状态转移:其余行列 + for i := 1; i < n; i++ { + for j := 1; j < m; j++ { + dp[i][j] = int(math.Min(float64(dp[i][j-1]), float64(dp[i-1][j]))) + grid[i][j] + } + } + return dp[n-1][m-1] + } ``` === "JavaScript" @@ -780,7 +839,27 @@ $$ === "Go" ```go title="min_path_sum.go" - [class]{}-[func]{minPathSumDPComp} + /* 最小路径和:状态压缩后的动态规划 */ + func minPathSumDPComp(grid [][]int) int { + n, m := len(grid), len(grid[0]) + // 初始化 dp 表 + dp := make([]int, m) + // 状态转移:首行 + dp[0] = grid[0][0] + for j := 1; j < m; j++ { + dp[j] = dp[j-1] + grid[0][j] + } + // 状态转移:其余行列 + for i := 1; i < n; i++ { + // 状态转移:首列 + dp[0] = dp[0] + grid[i][0] + // 状态转移:其余列 + for j := 1; j < m; j++ { + dp[j] = int(math.Min(float64(dp[j-1]), float64(dp[j]))) + grid[i][j] + } + } + return dp[m-1] + } ``` === "JavaScript" diff --git a/chapter_dynamic_programming/edit_distance_problem.md b/chapter_dynamic_programming/edit_distance_problem.md index 1e8c1b531..a16bbcc39 100644 --- a/chapter_dynamic_programming/edit_distance_problem.md +++ b/chapter_dynamic_programming/edit_distance_problem.md @@ -161,7 +161,35 @@ $$ === "Go" ```go title="edit_distance.go" - [class]{}-[func]{editDistanceDP} + /* 编辑距离:动态规划 */ + func editDistanceDP(s string, t string) int { + n := len(s) + m := len(t) + dp := make([][]int, n+1) + for i := 0; i <= n; i++ { + dp[i] = make([]int, m+1) + } + // 状态转移:首行首列 + for i := 1; i <= n; i++ { + dp[i][0] = i + } + for j := 1; j <= m; j++ { + dp[0][j] = j + } + // 状态转移:其余行列 + for i := 1; i <= n; i++ { + for j := 1; j <= m; j++ { + if s[i-1] == t[j-1] { + // 若两字符相等,则直接跳过此两字符 + dp[i][j] = dp[i-1][j-1] + } else { + // 最少编辑步数 = 插入、删除、替换这三种操作的最少编辑步数 + 1 + dp[i][j] = MinInt(MinInt(dp[i][j-1], dp[i-1][j]), dp[i-1][j-1]) + 1 + } + } + } + return dp[n][m] + } ``` === "JavaScript" @@ -430,7 +458,35 @@ $$ === "Go" ```go title="edit_distance.go" - [class]{}-[func]{editDistanceDPComp} + /* 编辑距离:状态压缩后的动态规划 */ + func editDistanceDPComp(s string, t string) int { + n := len(s) + m := len(t) + dp := make([]int, m+1) + // 状态转移:首行 + for j := 1; j <= m; j++ { + dp[j] = j + } + // 状态转移:其余行 + for i := 1; i <= n; i++ { + // 状态转移:首列 + leftUp := dp[0] // 暂存 dp[i-1, j-1] + dp[0] = i + // 状态转移:其余列 + for j := 1; j <= m; j++ { + temp := dp[j] + if s[i-1] == t[j-1] { + // 若两字符相等,则直接跳过此两字符 + dp[j] = leftUp + } else { + // 最少编辑步数 = 插入、删除、替换这三种操作的最少编辑步数 + 1 + dp[j] = MinInt(MinInt(dp[j-1], dp[j]), leftUp) + 1 + } + leftUp = temp // 更新为下一轮的 dp[i-1, j-1] + } + } + return dp[m] + } ``` === "JavaScript" diff --git a/chapter_dynamic_programming/intro_to_dynamic_programming.md b/chapter_dynamic_programming/intro_to_dynamic_programming.md index 20d6dbaae..389ba6c47 100644 --- a/chapter_dynamic_programming/intro_to_dynamic_programming.md +++ b/chapter_dynamic_programming/intro_to_dynamic_programming.md @@ -109,9 +109,36 @@ status: new === "Go" ```go title="climbing_stairs_backtrack.go" - [class]{}-[func]{backtrack} + /* 回溯 */ + func backtrack(choices []int, state, n int, res []int) { + // 当爬到第 n 阶时,方案数量加 1 + if state == n { + res[0] = res[0] + 1 + } + // 遍历所有选择 + for _, choice := range choices { + // 剪枝:不允许越过第 n 阶 + if state+choice > n { + break + } + // 尝试:做出选择,更新状态 + backtrack(choices, state+choice, n, res) + // 回退 + } + } - [class]{}-[func]{climbingStairsBacktrack} + /* 爬楼梯:回溯 */ + func climbingStairsBacktrack(n int) int { + // 可选择向上爬 1 或 2 阶 + choices := []int{1, 2} + // 从第 0 阶开始爬 + state := 0 + res := make([]int, 1) + // 使用 res[0] 记录方案数量 + res[0] = 0 + backtrack(choices, state, n, res) + return res[0] + } ``` === "JavaScript" @@ -324,9 +351,21 @@ $$ === "Go" ```go title="climbing_stairs_dfs.go" - [class]{}-[func]{dfs} + /* 搜索 */ + func dfs(i int) int { + // 已知 dp[1] 和 dp[2] ,返回之 + if i == 1 || i == 2 { + return i + } + // dp[i] = dp[i-1] + dp[i-2] + count := dfs(i-1) + dfs(i-2) + return count + } - [class]{}-[func]{climbingStairsDFS} + /* 爬楼梯:搜索 */ + func climbingStairsDFS(n int) int { + return dfs(n) + } ``` === "JavaScript" @@ -515,9 +554,32 @@ $$ === "Go" ```go title="climbing_stairs_dfs_mem.go" - [class]{}-[func]{dfs} + /* 记忆化搜索 */ + func dfsMem(i int, mem []int) int { + // 已知 dp[1] 和 dp[2] ,返回之 + if i == 1 || i == 2 { + return i + } + // 若存在记录 dp[i] ,则直接返回之 + if mem[i] != -1 { + return mem[i] + } + // dp[i] = dp[i-1] + dp[i-2] + count := dfsMem(i-1, mem) + dfsMem(i-2, mem) + // 记录 dp[i] + mem[i] = count + return count + } - [class]{}-[func]{climbingStairsDFSMem} + /* 爬楼梯:记忆化搜索 */ + func climbingStairsDFSMem(n int) int { + // mem[i] 记录爬到第 i 阶的方案总数,-1 代表无记录 + mem := make([]int, n+1) + for i := range mem { + mem[i] = -1 + } + return dfsMem(n, mem) + } ``` === "JavaScript" @@ -709,7 +771,22 @@ $$ === "Go" ```go title="climbing_stairs_dp.go" - [class]{}-[func]{climbingStairsDP} + /* 爬楼梯:动态规划 */ + func climbingStairsDP(n int) int { + if n == 1 || n == 2 { + return n + } + // 初始化 dp 表,用于存储子问题的解 + dp := make([]int, n+1) + // 初始状态:预设最小子问题的解 + dp[1] = 1 + dp[2] = 2 + // 状态转移:从较小子问题逐步求解较大子问题 + for i := 3; i <= n; i++ { + dp[i] = dp[i-1] + dp[i-2] + } + return dp[n] + } ``` === "JavaScript" @@ -863,7 +940,18 @@ $$ === "Go" ```go title="climbing_stairs_dp.go" - [class]{}-[func]{climbingStairsDPComp} + /* 爬楼梯:状态压缩后的动态规划 */ + func climbingStairsDPComp(n int) int { + if n == 1 || n == 2 { + return n + } + a, b := 1, 2 + // 状态转移:从较小子问题逐步求解较大子问题 + for i := 3; i <= n; i++ { + a, b = b, a+b + } + return b + } ``` === "JavaScript" diff --git a/chapter_dynamic_programming/knapsack_problem.md b/chapter_dynamic_programming/knapsack_problem.md index 21f1d306b..bd1dd70b6 100644 --- a/chapter_dynamic_programming/knapsack_problem.md +++ b/chapter_dynamic_programming/knapsack_problem.md @@ -127,7 +127,22 @@ $$ === "Go" ```go title="knapsack.go" - [class]{}-[func]{knapsackDFS} + /* 0-1 背包:暴力搜索 */ + func knapsackDFS(wgt, val []int, i, c int) int { + // 若已选完所有物品或背包无容量,则返回价值 0 + if i == 0 || c == 0 { + return 0 + } + // 若超过背包容量,则只能不放入背包 + if wgt[i-1] > c { + return knapsackDFS(wgt, val, i-1, c) + } + // 计算不放入和放入物品 i 的最大价值 + no := knapsackDFS(wgt, val, i-1, c) + yes := knapsackDFS(wgt, val, i-1, c-wgt[i-1]) + val[i-1] + // 返回两种方案中价值更大的那一个 + return int(math.Max(float64(no), float64(yes))) + } ``` === "JavaScript" @@ -308,7 +323,27 @@ $$ === "Go" ```go title="knapsack.go" - [class]{}-[func]{knapsackDFSMem} + /* 0-1 背包:记忆化搜索 */ + func knapsackDFSMem(wgt, val []int, mem [][]int, i, c int) int { + // 若已选完所有物品或背包无容量,则返回价值 0 + if i == 0 || 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 的最大价值 + no := knapsackDFSMem(wgt, val, mem, i-1, c) + yes := knapsackDFSMem(wgt, val, mem, i-1, c-wgt[i-1]) + val[i-1] + // 返回两种方案中价值更大的那一个 + mem[i][c] = int(math.Max(float64(no), float64(yes))) + return mem[i][c] + } ``` === "JavaScript" @@ -494,7 +529,28 @@ $$ === "Go" ```go title="knapsack.go" - [class]{}-[func]{knapsackDP} + /* 0-1 背包:动态规划 */ + func knapsackDP(wgt, val []int, cap int) int { + n := len(wgt) + // 初始化 dp 表 + dp := make([][]int, n+1) + for i := 0; i <= n; i++ { + dp[i] = make([]int, cap+1) + } + // 状态转移 + for i := 1; i <= n; i++ { + for c := 1; c <= cap; c++ { + if wgt[i-1] > c { + // 若超过背包容量,则不选物品 i + dp[i][c] = dp[i-1][c] + } else { + // 不选和选物品 i 这两种方案的较大值 + dp[i][c] = int(math.Max(float64(dp[i-1][c]), float64(dp[i-1][c-wgt[i-1]]+val[i-1]))) + } + } + } + return dp[n][cap] + } ``` === "JavaScript" @@ -733,7 +789,23 @@ $$ === "Go" ```go title="knapsack.go" - [class]{}-[func]{knapsackDPComp} + /* 0-1 背包:状态压缩后的动态规划 */ + func knapsackDPComp(wgt, val []int, cap int) int { + n := len(wgt) + // 初始化 dp 表 + dp := make([]int, cap+1) + // 状态转移 + for i := 1; i <= n; i++ { + // 倒序遍历 + for c := cap; c >= 1; c-- { + if wgt[i-1] <= c { + // 不选和选物品 i 这两种方案的较大值 + dp[c] = int(math.Max(float64(dp[c]), float64(dp[c-wgt[i-1]]+val[i-1]))) + } + } + } + return dp[cap] + } ``` === "JavaScript" diff --git a/chapter_dynamic_programming/unbounded_knapsack_problem.md b/chapter_dynamic_programming/unbounded_knapsack_problem.md index c8aea2b36..8999a03fe 100644 --- a/chapter_dynamic_programming/unbounded_knapsack_problem.md +++ b/chapter_dynamic_programming/unbounded_knapsack_problem.md @@ -108,7 +108,28 @@ $$ === "Go" ```go title="unbounded_knapsack.go" - [class]{}-[func]{unboundedKnapsackDP} + /* 完全背包:动态规划 */ + func unboundedKnapsackDP(wgt, val []int, cap int) int { + n := len(wgt) + // 初始化 dp 表 + dp := make([][]int, n+1) + for i := 0; i <= n; i++ { + dp[i] = make([]int, cap+1) + } + // 状态转移 + for i := 1; i <= n; i++ { + for c := 1; c <= cap; c++ { + if wgt[i-1] > c { + // 若超过背包容量,则不选物品 i + dp[i][c] = dp[i-1][c] + } else { + // 不选和选物品 i 这两种方案的较大值 + dp[i][c] = int(math.Max(float64(dp[i-1][c]), float64(dp[i][c-wgt[i-1]]+val[i-1]))) + } + } + } + return dp[n][cap] + } ``` === "JavaScript" @@ -303,7 +324,25 @@ $$ === "Go" ```go title="unbounded_knapsack.go" - [class]{}-[func]{unboundedKnapsackDPComp} + /* 完全背包:状态压缩后的动态规划 */ + func unboundedKnapsackDPComp(wgt, val []int, cap int) int { + n := len(wgt) + // 初始化 dp 表 + dp := make([]int, cap+1) + // 状态转移 + for i := 1; i <= n; i++ { + for c := 1; c <= cap; c++ { + if wgt[i-1] > c { + // 若超过背包容量,则不选物品 i + dp[c] = dp[c] + } else { + // 不选和选物品 i 这两种方案的较大值 + dp[c] = int(math.Max(float64(dp[c]), float64(dp[c-wgt[i-1]]+val[i-1]))) + } + } + } + return dp[cap] + } ``` === "JavaScript" @@ -536,7 +575,36 @@ $$ === "Go" ```go title="coin_change.go" - [class]{}-[func]{coinChangeDP} + /* 零钱兑换:动态规划 */ + func coinChangeDP(coins []int, amt int) int { + n := len(coins) + max := amt + 1 + // 初始化 dp 表 + dp := make([][]int, n+1) + for i := 0; i <= n; i++ { + dp[i] = make([]int, amt+1) + } + // 状态转移:首行首列 + for a := 1; a <= amt; a++ { + dp[0][a] = max + } + // 状态转移:其余行列 + for i := 1; i <= n; i++ { + for a := 1; a <= amt; a++ { + if coins[i-1] > a { + // 若超过背包容量,则不选硬币 i + dp[i][a] = dp[i-1][a] + } else { + // 不选和选硬币 i 这两种方案的较小值 + dp[i][a] = int(math.Min(float64(dp[i-1][a]), float64(dp[i][a-coins[i-1]]+1))) + } + } + } + if dp[n][amt] != max { + return dp[n][amt] + } + return -1 + } ``` === "JavaScript" @@ -784,7 +852,33 @@ $$ === "Go" ```go title="coin_change.go" - [class]{}-[func]{coinChangeDPComp} + /* 零钱兑换:动态规划 */ + func coinChangeDPComp(coins []int, amt int) int { + n := len(coins) + max := amt + 1 + // 初始化 dp 表 + dp := make([]int, amt+1) + for i := 1; i <= amt; i++ { + dp[i] = max + } + // 状态转移 + for i := 1; i <= n; i++ { + // 倒序遍历 + for a := 1; a <= amt; a++ { + if coins[i-1] > a { + // 若超过背包容量,则不选硬币 i + dp[a] = dp[a] + } else { + // 不选和选硬币 i 这两种方案的较小值 + dp[a] = int(math.Min(float64(dp[a]), float64(dp[a-coins[i-1]]+1))) + } + } + } + if dp[amt] != max { + return dp[amt] + } + return -1 + } ``` === "JavaScript" @@ -999,7 +1093,32 @@ $$ === "Go" ```go title="coin_change_ii.go" - [class]{}-[func]{coinChangeIIDP} + /* 零钱兑换 II:动态规划 */ + func coinChangeIIDP(coins []int, amt int) int { + n := len(coins) + // 初始化 dp 表 + dp := make([][]int, n+1) + for i := 0; i <= n; i++ { + dp[i] = make([]int, amt+1) + } + // 初始化首列 + for i := 0; i <= n; i++ { + dp[i][0] = 1 + } + // 状态转移:其余行列 + for i := 1; i <= n; i++ { + for a := 1; a <= amt; a++ { + if coins[i-1] > a { + // 若超过背包容量,则不选硬币 i + dp[i][a] = dp[i-1][a] + } else { + // 不选和选硬币 i 这两种方案的较小值 + dp[i][a] = dp[i-1][a] + dp[i][a-coins[i-1]] + } + } + } + return dp[n][amt] + } ``` === "JavaScript" @@ -1189,7 +1308,27 @@ $$ === "Go" ```go title="coin_change_ii.go" - [class]{}-[func]{coinChangeIIDPComp} + /* 零钱兑换 II:状态压缩后的动态规划 */ + func coinChangeIIDPComp(coins []int, amt int) int { + n := len(coins) + // 初始化 dp 表 + dp := make([]int, amt+1) + dp[0] = 1 + // 状态转移 + for i := 1; i <= n; i++ { + // 倒序遍历 + for a := 1; a <= amt; a++ { + if coins[i-1] > a { + // 若超过背包容量,则不选硬币 i + dp[a] = dp[a] + } else { + // 不选和选硬币 i 这两种方案之和 + dp[a] = dp[a] + dp[a-coins[i-1]] + } + } + } + return dp[amt] + } ``` === "JavaScript" diff --git a/chapter_greedy/fractional_knapsack_problem.md b/chapter_greedy/fractional_knapsack_problem.md index d9a297477..769348f50 100644 --- a/chapter_greedy/fractional_knapsack_problem.md +++ b/chapter_greedy/fractional_knapsack_problem.md @@ -157,9 +157,39 @@ status: new === "Go" ```go title="fractional_knapsack.go" - [class]{}-[func]{II} + /* 物品 */ + type Item struct { + w int // 物品重量 + v int // 物品价值 + } - [class]{}-[func]{fractionalKnapsack} + /* 分数背包:贪心 */ + func fractionalKnapsack(wgt []int, val []int, cap int) float64 { + // 创建物品列表,包含两个属性:重量、价值 + items := make([]Item, len(wgt)) + for i := 0; i < len(wgt); i++ { + items[i] = Item{wgt[i], val[i]} + } + // 按照单位价值 item.v / item.w 从高到低进行排序 + sort.Slice(items, func(i, j int) bool { + return float64(items[i].v)/float64(items[i].w) > float64(items[j].v)/float64(items[j].w) + }) + // 循环贪心选择 + res := 0.0 + for _, item := range items { + if item.w <= cap { + // 若剩余容量充足,则将当前物品整个装进背包 + res += float64(item.v) + cap -= item.w + } else { + // 若剩余容量不足,则将当前物品的一部分装进背包 + res += float64(item.v) / float64(item.w) * float64(cap) + // 已无剩余容量,因此跳出循环 + break + } + } + return res + } ``` === "JavaScript" diff --git a/chapter_greedy/greedy_algorithm.md b/chapter_greedy/greedy_algorithm.md index fe133d299..14bc711aa 100644 --- a/chapter_greedy/greedy_algorithm.md +++ b/chapter_greedy/greedy_algorithm.md @@ -95,7 +95,27 @@ status: new === "Go" ```go title="coin_change_greedy.go" - [class]{}-[func]{coinChangeGreedy} + /* 零钱兑换:贪心 */ + func coinChangeGreedy(coins []int, amt int) int { + // 假设 coins 列表有序 + i := len(coins) - 1 + count := 0 + // 循环进行贪心选择,直到无剩余金额 + for amt > 0 { + // 找到小于且最接近剩余金额的硬币 + for coins[i] > amt { + i-- + } + // 选择 coins[i] + amt -= coins[i] + count++ + } + // 若未找到可行方案,则返回 -1 + if amt != 0 { + return -1 + } + return count + } ``` === "JavaScript" diff --git a/chapter_greedy/max_capacity_problem.md b/chapter_greedy/max_capacity_problem.md index de6909034..7e9a0b84d 100644 --- a/chapter_greedy/max_capacity_problem.md +++ b/chapter_greedy/max_capacity_problem.md @@ -161,7 +161,26 @@ $$ === "Go" ```go title="max_capacity.go" - [class]{}-[func]{maxCapacity} + /* 最大容量:贪心 */ + func maxCapacity(ht []int) int { + // 初始化 i, j 分列数组两端 + i, j := 0, len(ht)-1 + // 初始最大容量为 0 + res := 0 + // 循环贪心选择,直至两板相遇 + for i < j { + // 更新最大容量 + capacity := int(math.Min(float64(ht[i]), float64(ht[j]))) * (j - i) + res = int(math.Max(float64(res), float64(capacity))) + // 向内移动短板 + if ht[i] < ht[j] { + i++ + } else { + j-- + } + } + return res + } ``` === "JavaScript" diff --git a/chapter_greedy/max_product_cutting_problem.md b/chapter_greedy/max_product_cutting_problem.md index 79c7cbb84..1be00ec30 100644 --- a/chapter_greedy/max_product_cutting_problem.md +++ b/chapter_greedy/max_product_cutting_problem.md @@ -147,7 +147,26 @@ $$ === "Go" ```go title="max_product_cutting.go" - [class]{}-[func]{maxProductCutting} + /* 最大切分乘积:贪心 */ + func maxProductCutting(n int) int { + // 当 n <= 3 时,必须切分出一个 1 + if n <= 3 { + return 1 * (n - 1) + } + // 贪心地切分出 3 ,a 为 3 的个数,b 为余数 + a := n / 3 + b := n % 3 + if b == 1 { + // 当余数为 1 时,将一对 1 * 3 转化为 2 * 2 + return int(math.Pow(3, float64(a-1))) * 2 * 2 + } + if b == 2 { + // 当余数为 2 时,不做处理 + return int(math.Pow(3, float64(a))) * 2 + } + // 当余数为 0 时,不做处理 + return int(math.Pow(3, float64(a))) + } ``` === "JavaScript" diff --git a/chapter_heap/top_k.md b/chapter_heap/top_k.md index b80d6fc56..41662a800 100644 --- a/chapter_heap/top_k.md +++ b/chapter_heap/top_k.md @@ -139,7 +139,24 @@ comments: true === "Go" ```go title="top_k.go" - [class]{maxHeap}-[func]{topKHeap} + /* 基于堆查找数组中最大的 k 个元素 */ + func topKHeap(nums []int, k int) *minHeap { + h := &minHeap{} + heap.Init(h) + // 将数组的前 k 个元素入堆 + for i := 0; i < k; i++ { + heap.Push(h, nums[i]) + } + // 从第 k+1 个元素开始,保持堆的长度为 k + for i := k; i < len(nums); i++ { + // 若当前元素大于堆顶元素,则将堆顶元素出堆、当前元素入堆 + if nums[i] > h.Top().(int) { + heap.Pop(h) + heap.Push(h, nums[i]) + } + } + return h + } ``` === "JavaScript" @@ -157,7 +174,7 @@ comments: true === "C" ```c title="top_k.c" - [class]{maxHeap}-[func]{topKHeap} + [class]{}-[func]{topKHeap} ``` === "C#" diff --git a/chapter_tree/array_representation_of_tree.md b/chapter_tree/array_representation_of_tree.md index d20dd132b..936e67c5e 100644 --- a/chapter_tree/array_representation_of_tree.md +++ b/chapter_tree/array_representation_of_tree.md @@ -513,7 +513,99 @@ comments: true === "Swift" ```swift title="array_binary_tree.swift" - [class]{ArrayBinaryTree}-[func]{} + /* 数组表示下的二叉树类 */ + class ArrayBinaryTree { + private var tree: [Int?] + + /* 构造方法 */ + init(arr: [Int?]) { + tree = arr + } + + /* 节点数量 */ + func size() -> Int { + tree.count + } + + /* 获取索引为 i 节点的值 */ + func val(i: Int) -> Int? { + // 若索引越界,则返回 null ,代表空位 + if i < 0 || i >= size() { + return nil + } + return tree[i] + } + + /* 获取索引为 i 节点的左子节点的索引 */ + func left(i: Int) -> Int { + 2 * i + 1 + } + + /* 获取索引为 i 节点的右子节点的索引 */ + func right(i: Int) -> Int { + 2 * i + 2 + } + + /* 获取索引为 i 节点的父节点的索引 */ + func parent(i: Int) -> Int { + (i - 1) / 2 + } + + /* 层序遍历 */ + func levelOrder() -> [Int] { + var res: [Int] = [] + // 直接遍历数组 + for i in stride(from: 0, to: size(), by: 1) { + if let val = val(i: i) { + res.append(val) + } + } + return res + } + + /* 深度优先遍历 */ + private func dfs(i: Int, order: String, res: inout [Int]) { + // 若为空位,则返回 + guard let val = val(i: i) else { + return + } + // 前序遍历 + if order == "pre" { + res.append(val) + } + dfs(i: left(i: i), order: order, res: &res) + // 中序遍历 + if order == "in" { + res.append(val) + } + dfs(i: right(i: i), order: order, res: &res) + // 后序遍历 + if order == "post" { + res.append(val) + } + } + + /* 前序遍历 */ + func preOrder() -> [Int] { + var res: [Int] = [] + dfs(i: 0, order: "pre", res: &res) + return res + } + + /* 中序遍历 */ + func inOrder() -> [Int] { + var res: [Int] = [] + dfs(i: 0, order: "in", res: &res) + return res + } + + /* 后序遍历 */ + func postOrder() -> [Int] { + var res: [Int] = [] + dfs(i: 0, order: "post", res: &res) + return res + } + } ``` === "Zig" diff --git a/chapter_tree/avl_tree.md b/chapter_tree/avl_tree.md index 6cf7f821d..e1335440a 100644 --- a/chapter_tree/avl_tree.md +++ b/chapter_tree/avl_tree.md @@ -1613,7 +1613,6 @@ AVL 树的特点在于「旋转 Rotation」操作,它能够在不影响二叉 ```swift title="avl_tree.swift" /* 插入节点 */ - @discardableResult func insert(val: Int) { root = insertHelper(node: root, val: val) } @@ -2067,7 +2066,6 @@ AVL 树的特点在于「旋转 Rotation」操作,它能够在不影响二叉 ```swift title="avl_tree.swift" /* 删除节点 */ - @discardableResult func remove(val: Int) { root = removeHelper(node: root, val: val) } diff --git a/chapter_tree/binary_search_tree.md b/chapter_tree/binary_search_tree.md index 75ededf53..0c2979ca0 100755 --- a/chapter_tree/binary_search_tree.md +++ b/chapter_tree/binary_search_tree.md @@ -1103,7 +1103,6 @@ comments: true ```swift title="binary_search_tree.swift" /* 删除节点 */ - @discardableResult func remove(num: Int) { // 若树为空,直接提前返回 if root == nil {