mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Update 0746.使用最小花费爬楼梯.md
This commit is contained in:
@ -282,7 +282,35 @@ class Solution:
|
|||||||
return dp1 # 返回到达楼顶的最小花费
|
return dp1 # 返回到达楼顶的最小花费
|
||||||
|
|
||||||
```
|
```
|
||||||
|
动态规划(版本三)
|
||||||
|
|
||||||
|
```python
|
||||||
|
class Solution:
|
||||||
|
def minCostClimbingStairs(self, cost: List[int]) -> int:
|
||||||
|
dp = [0] * len(cost)
|
||||||
|
dp[0] = cost[0] # 第一步有花费
|
||||||
|
dp[1] = cost[1]
|
||||||
|
for i in range(2, len(cost)):
|
||||||
|
dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i]
|
||||||
|
# 注意最后一步可以理解为不用花费,所以取倒数第一步,第二步的最少值
|
||||||
|
return min(dp[-1], dp[-2])
|
||||||
|
|
||||||
|
```
|
||||||
|
动态规划(版本四)
|
||||||
|
|
||||||
|
```python
|
||||||
|
class Solution:
|
||||||
|
def minCostClimbingStairs(self, cost: List[int]) -> int:
|
||||||
|
n = len(cost)
|
||||||
|
prev_1 = cost[0] # 前一步的最小花费
|
||||||
|
prev_2 = cost[1] # 前两步的最小花费
|
||||||
|
for i in range(2, n):
|
||||||
|
current = min(prev_1, prev_2) + cost[i] # 当前位置的最小花费
|
||||||
|
prev_1, prev_2 = prev_2, current # 更新前一步和前两步的最小花费
|
||||||
|
return min(prev_1, prev_2) # 最后一步可以理解为不用花费,取倒数第一步和第二步的最少值
|
||||||
|
|
||||||
|
|
||||||
|
```
|
||||||
### Go
|
### Go
|
||||||
```Go
|
```Go
|
||||||
func minCostClimbingStairs(cost []int) int {
|
func minCostClimbingStairs(cost []int) int {
|
||||||
|
Reference in New Issue
Block a user