leecode 1054. Min Cost Climbing Stairs

1054. Min Cost Climbing Stairs

Description
在楼梯上,每一号台阶都有各自的费用,即第 i 号台阶有非负成本cost [i](台阶从0号索引)。
一旦你支付了费用,你可以爬一到两步。 你需要找到最低成本来到达最高层,你可以从索引为0的楼梯开始,也可以从索引为1的楼梯开始。

Examples:

Input: cost = [10, 15, 20]
Output: 15
Explanation: Cheapest is start on cost[1], pay that cost and go to the top.

Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
Output: 6
Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3].

分析:分析该题可知该题为较为基础的动态规划问题,每一个台阶处的状态取决于前两个台阶的状态,因此分析题意列出动态转移方程即可解答。
令sum_cost_n[n]表示处于第n个台阶时所花费的最低cost,则我们可知sum_cost_n[0]和sum_cost_n[1]均为0,因为起始位置可以位于这两个位置。当n>=2时,我们可以列出如下式子:

sum_cost_n[n]=min(sum_cost_n[n-1]+cost[n-1],sum_cost_n[n-2]+cost[n-2])

故根据该方程进行遍历,最终sum_cost_n[n]即为所求
代码如下:python3

class Solution:
    """
    @param cost: an array
    @return: minimum cost to reach the top of the floor
    """
    def minCostClimbingStairs(self, cost):
        # Write your code here
        #sum_cost_n表示到达第n个台阶的最少消耗
        if len(cost)<=2:
            return 0
        sum_cost_n=[0]*(len(cost)+1) #初始化数组
        sum_cost_n[0]=sum_cost_n[1]=0  #初始化第0和第1个台阶处的值
        for each in range(2,len(cost)+1):
            sum_cost_n[each]=min(sum_cost_n[each-1]+cost[each-1],sum_cost_n[each-2]+cost[each-2])
        return sum_cost_n[len(cost)]
            
            
            
        

发布了68 篇原创文章 · 获赞 36 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/dingdingdodo/article/details/100782440