【Leetcode】Min Cost Climbing Stairs

On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).

Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1.

class Solution(object):

    def minCostClimbingStairs(self, cost):

        """

        :type cost: List[int]

        :rtype: int

        """

        a = 0

        b = 0

        for i in xrange(2, len(cost)+1):

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

        return b

1 想要达到i-th台阶,可以从i-1-th台阶爬一步到达,需要cost[i-1], 或者从i-2-th台阶爬两步到达,需要cost[i-2],所以到达i-th台阶所需要的最小cost=min(f(i-1)+cost[i-1], f(i-2)+cost[i-2])

2 初始化很重要,因为说可以从0-th开始,也可以从1-th开始,所以初始值,在0-th开始的cost是0,在1-th开始的cost也是0

3 xrange是从2到len(cost)+1,这是因为cost的长度是n-1,即在n-1台阶上,pay cost[-1],我们还可以爬一楼

4 为了减少空间复杂度,可以只存储previous的两个值就可以了

你可能感兴趣的:(【Leetcode】Min Cost Climbing Stairs)