代码随想录算法训练营第二十九天| 509. 斐波那契数、70. 爬楼梯、746. 使用最小花费爬楼梯
题目链接:509. 斐波那契数 - 力扣(LeetCode)
思路:基础题目
class Solution(object):def fib(self, n):""":type n: int:rtype: int"""if n == 0:return 0elif n == 1: return 1else:dp = [0] * (n + 1)dp[0] = 0dp[1] = 1for i in range(2, n + 1):dp[i] = dp[i - 1] + dp[i - 2]return dp[n]
题目链接:70. 爬楼梯 - 力扣(LeetCode)
class Solution(object):def climbStairs(self, n):""":type n: int:rtype: int"""if n == 1:return 1elif n == 2:return 2else:dp = [0] * (n + 1) #多一个防止排0dp[1] = 1 #上一阶有一种 1dp[2] = 2 #上二阶有两种 1 + 1; 2for i in range(3, n + 1):dp[i] = dp[i-2] + dp[i-1] #由下两阶跨两步上来,也可以下一阶跨一步上来return dp[n]
题目链接:746. 使用最小花费爬楼梯 - 力扣(LeetCode)
思路:这题主要是要想清楚楼顶在哪,要多加一位
class Solution(object):def minCostClimbingStairs(self, cost):""":type cost: List[int]:rtype: int"""if len(cost) == 2:return min(cost[0], cost[1])else:dp = [0] * (len(cost) + 1) #dp数组代表走到当前位置需要花费的最小代价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)]
