746. Min Cost Climbing Stairs

问题

在一个楼梯上,cost[i]表示第i个梯子的代价,只要你付出这个代价就可以爬一步或两步,你可以从index 0开始或者index 1开始爬。求爬到顶部(cost的index从0到n-1,要爬到index n的梯子上)的最小代价。cost的长度至少为2。

Input: cost = [10, 15, 20]
Output: 15
Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
Output: 6

思路

做法1:dp[i]表示到达i个阶梯需要付出的最小代价,因为可以跳一步或两步,dp[i]可以表示为前一个阶梯跳过来和前两个阶梯跳过来花费的代价的最小值,dp公式为:(dp[i] = min(dp[i-1]+cos[i-1], dp[i-2]+cost[i-2]))

时间复杂度O(n),空间复杂度O(n)

做法2:考虑到每次dp的值dp[i]只取决于前面两个值dp[i-1]和dp[i-2],可以使用两个临时变量f1和f2来代替,这样可以省下dp数组的空间开销。

时间复杂度O(n),空间复杂度O(1)

代码

做法1

class Solution(object):
    def minCostClimbingStairs(self, cost):
        """
        :type cost: List[int]
        :rtype: int
        """
        dp = [0] * (len(cost)+1)
        for i in range(2,len(cost)+1):
            dp[i] = min(dp[i-1]+cost[i-1], dp[i-2]+cost[i-2])
        return dp[len(cost)]   

做法2

class Solution(object):
    def minCostClimbingStairs(self, cost):
        """
        :type cost: List[int]
        :rtype: int
        """
        f1 = f2 = 0
        for i in range(2,len(cost)+1):
            f1, f2 = min(f1+cost[i-1], f2+cost[i-2]), f1
        return f1   
原文地址:https://www.cnblogs.com/liaohuiqiang/p/9745614.html