代码随想录day38|509. 斐波那契数70. 爬楼梯746. 使用最小花费爬楼梯

509. 斐波那契数

class Solution:
    def fib(self, n: int) -> int:
        #dp含义,递推公式,dp初始化,遍历顺序,打印dp
        if n == 0:
            return 0
        dp = [0] * (n+1)
        dp[0]=0
        dp[1]=1
        for i in range(2,n+1):
            dp[i] = dp[i-1] +dp[i-2]
        return dp[n]

70. 爬楼梯

class Solution:
    def climbStairs(self, n: int) -> int:
        dp = [0] * (n+1)
        dp[0] = 1
        dp[1] = 1
        for i in range(2,n+1):
            dp[i] = dp[i-1] +dp[i-2]
        return dp[n]

746. 使用最小花费爬楼梯

class Solution:
    def minCostClimbingStairs(self, cost: List[int]) -> int:
        dp = [0] *(len(cost)+1)
        dp[0]=0
        dp[1]=0
        i=2
        while i <=len(cost):
            dp[i]=min(cost[i-1]+dp[i-1],cost[i-2]+dp[i-2])
            i+=1
        return dp[len(cost)]

你可能感兴趣的:(算法,leetcode,动态规划)