509. 斐波那契数:
代码思路
dp[i]代表F(i),然后前面的推后面的,也就是所谓状态转移方程(题目已给出)
class Solution:
def fib(self, n: int) -> int:
if n < 2:
return n
dp = [-1 for i in range(n+1)]
dp[0] = 0
dp[1] = 1
i = 2
while i <= n:
dp[i] = dp[i-1] + dp[i-2]
i += 1
return dp[n]
70. 爬楼梯:
代码思路
和斐波那契一模一样
class Solution:
def climbStairs(self, n: int) -> int:
if n <= 2:
return n
dp = [-1 for i in range(n+1)]
dp[1] = 1
dp[2] = 2
i = 3
while i <= n:
dp[i] = dp[i-1] + dp[i - 2]
i += 1
return dp[n]
746. 使用最小花费爬楼梯:
代码思路
固定套路,一阶动规。
class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
dp = [-1 for i in range(len(cost)+1)]
dp[0] = cost[0]
dp[1] = cost[1]
i = 2
while i < len(cost):
dp[i] = min(dp[i-2]+cost[i], dp[i-1]+cost[i])
i += 1
return min(dp[len(cost)-1], dp[len(cost)-2])