每日一题20201221(746. 使用最小花费爬楼梯)

746. 使用最小花费爬楼梯

image-20201221144706713

思路

用动态规划的思想去做, 只要跳到倒数第二阶和倒数第一阶的时候,可以完成跳跃操作。

维护一个数组,存放跳到每阶时候的最小花费。设到i阶的时候,它有可能是从i-2阶跳上来的,也可能是i-1跳上来的,所以:

f(i) = min(f(i-1)+cost[i], f(i-2)+cost[i])

class Solution:
    def minCostClimbingStairs(self, cost: List[int]) -> int:
        dp = [0] * len(cost)
        for n in range(len(cost)):
            # 选取起点
            if n < 2:
                dp[n] = cost[n]
            else:
                dp[n] = min(dp[n-1]+cost[n], dp[n-2]+cost[n])
        return min(dp[len(cost)-1], dp[len(cost)-2])

image-20201221145717554

扩展

你能优化下内存🐴?考虑不使用额外的空间!
class Solution:
    def minCostClimbingStairs(self, cost: List[int]) -> int:
        if len(cost) <= 2:
            return min(cost)
        prev, current = cost[0], cost[1]
        for i in range(2, len(cost)):
            prev, current = current, min(prev+cost[i], current+cost[i])
        return min(prev, current)
posted @ 2020-12-21 15:00  米洛丶  阅读(94)  评论(0)    收藏  举报