This commit is contained in:
krahets
2023-07-19 01:44:39 +08:00
parent ec6f3fd337
commit 1184c791c5
14 changed files with 563 additions and 42 deletions
@@ -143,7 +143,23 @@ $$
=== "Swift"
```swift title="min_cost_climbing_stairs_dp.swift"
[class]{}-[func]{minCostClimbingStairsDP}
/* 爬楼梯最小代价:动态规划 */
func minCostClimbingStairsDP(cost: [Int]) -> Int {
let n = cost.count - 1
if n == 1 || n == 2 {
return cost[n]
}
// 初始化 dp 表,用于存储子问题的解
var dp = Array(repeating: 0, count: n + 1)
// 初始状态:预设最小子问题的解
dp[1] = 1
dp[2] = 2
// 状态转移:从较小子问题逐步求解较大子问题
for i in stride(from: 3, through: n, by: 1) {
dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i]
}
return dp[n]
}
```
=== "Zig"
@@ -275,7 +291,18 @@ $$
=== "Swift"
```swift title="min_cost_climbing_stairs_dp.swift"
[class]{}-[func]{minCostClimbingStairsDPComp}
/* 爬楼梯最小代价:状态压缩后的动态规划 */
func minCostClimbingStairsDPComp(cost: [Int]) -> Int {
let n = cost.count - 1
if n == 1 || n == 2 {
return cost[n]
}
var (a, b) = (cost[1], cost[2])
for i in stride(from: 3, through: n, by: 1) {
(a, b) = (b, min(a, b) + cost[i])
}
return b
}
```
=== "Zig"
@@ -465,7 +492,25 @@ $$
=== "Swift"
```swift title="climbing_stairs_constraint_dp.swift"
[class]{}-[func]{climbingStairsConstraintDP}
/* 带约束爬楼梯:动态规划 */
func climbingStairsConstraintDP(n: Int) -> Int {
if n == 1 || n == 2 {
return n
}
// 初始化 dp 表,用于存储子问题的解
var dp = Array(repeating: Array(repeating: 0, count: 3), count: n + 1)
// 初始状态:预设最小子问题的解
dp[1][1] = 1
dp[1][2] = 0
dp[2][1] = 0
dp[2][2] = 1
// 状态转移:从较小子问题逐步求解较大子问题
for i in stride(from: 3, through: n, by: 1) {
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]
}
```
=== "Zig"