From 50ed10475df9c62dae9e149a867a6f083a0dde04 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Mon, 12 Jun 2023 01:59:52 -0500 Subject: [PATCH] =?UTF-8?q?Update=200746.=E4=BD=BF=E7=94=A8=E6=9C=80?= =?UTF-8?q?=E5=B0=8F=E8=8A=B1=E8=B4=B9=E7=88=AC=E6=A5=BC=E6=A2=AF.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0746.使用最小花费爬楼梯.md | 28 ++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/problems/0746.使用最小花费爬楼梯.md b/problems/0746.使用最小花费爬楼梯.md index cd5e40e6..9eaaa4e9 100644 --- a/problems/0746.使用最小花费爬楼梯.md +++ b/problems/0746.使用最小花费爬楼梯.md @@ -282,7 +282,35 @@ class Solution: 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 func minCostClimbingStairs(cost []int) int {