746. Min Cost Climbing stairs

Source: Internet
Author: User

Problem

On a staircase, cost[i] represents the cost of the I-ladder, as long as you pay the price you can climb one or two steps, you can start from index 0 or index 1 to crawl. The minimum price to climb to the top (the cost index from 0 to n-1, to climb to the ladder on Index N). The cost is at least 2 of the length.

Ideas

Procedure 1: Dp[i] represents the minimum cost to reach the I ladder, as one or two steps can be skipped, dp[i] can represent the minimum value of the cost of jumping over the previous ladder and jumping over the first two steps, the DP formula is:\ (Dp[i] = min (dp[ I-1]+cos[i-1], dp[i-2]+cost[i-2]) \)

Time complexity O (n), spatial complexity O (n)

Procedure 2: Considering that the value of each DP Dp[i] depends only on the previous two values dp[i-1] and dp[i-2], you can use two temporary variables F1 and F2 instead, which saves the space overhead of the DP array.

Time complexity O (n), Spatial complexity O (1)

Code

Procedure 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)]   

Procedure 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   

746. Min Cost Climbing stairs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.