更新0746.使用最小花费爬楼梯.md 提供Go版本解法的新思路(dp[i]表示从i层起跳所需要支付的最小费用)

This commit is contained in:
jeffreyjia
2023-03-12 13:07:31 +08:00
parent 549d37a54e
commit 0ccbc1ea53
5 changed files with 58 additions and 0 deletions

View File

@@ -284,6 +284,33 @@ func min(a, b int) int {
return b
}
```
``` GO
第二种思路: dp[i]表示从i层起跳所需要支付的最小费用
递推公式:
i<n :dp[i] = min(dp[i-1],dp[i-2])+cost[i]
i==n:dp[i] = min(dp[i-1],dp[i-2]) (登顶)
func minCostClimbingStairs(cost []int) int {
n := len(cost)
dp := make([]int, n+1)
dp[0], dp[1] = cost[0], cost[1]
for i := 2; i <= n; i++ {
if i < n {
dp[i] = min(dp[i-1], dp[i-2]) + cost[i]
} else {
dp[i] = min(dp[i-1], dp[i-2])
}
}
return dp[n]
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
```
### Javascript
```Javascript