Skip to content

Commit 5d33abb

Browse files
Merge pull request youngyangyang04#1948 from HotPotJ/master
为【0749.使用最小花费爬楼梯】提供了另一种动态规划方程的思路 Go语言班班
2 parents edea08e + d34e4a8 commit 5d33abb

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

problems/0746.使用最小花费爬楼梯.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,33 @@ func min(a, b int) int {
284284
return b
285285
}
286286
```
287+
``` GO
288+
第二种思路: dp[i]表示从i层起跳所需要支付的最小费用
289+
递推公式:
290+
i<n :dp[i] = min(dp[i-1],dp[i-2])+cost[i]
291+
i==n:dp[i] = min(dp[i-1],dp[i-2]) (登顶)
292+
293+
func minCostClimbingStairs(cost []int) int {
294+
n := len(cost)
295+
dp := make([]int, n+1)
296+
dp[0], dp[1] = cost[0], cost[1]
297+
for i := 2; i <= n; i++ {
298+
if i < n {
299+
dp[i] = min(dp[i-1], dp[i-2]) + cost[i]
300+
} else {
301+
dp[i] = min(dp[i-1], dp[i-2])
302+
}
303+
}
304+
return dp[n]
305+
}
306+
func min(a, b int) int {
307+
if a < b {
308+
return a
309+
}
310+
return b
311+
}
312+
```
313+
287314

288315
### Javascript
289316
```Javascript

0 commit comments

Comments
 (0)