509. 斐波那契数
解题思路:动态规划
class Solution:
def fib(self, n: int) -> int:
# method 1
if n < 2: return n
# 1. 下标含义:dp[i]表示第i个斐波那契数列
dp = [0] * (n+1)
#3.数组初始化
dp[0] = 0
dp[1] = 1
#4.遍历顺序(从前向后)
for i in range(2,n+1):
#2.递推公式
dp[i] = dp[i-1] + dp[i-2]
return dp[n]
70. 爬楼梯
解题思路:动态规划
class Solution:
def climbStairs(self, n: int) -> int:
# method1
#1.dp[i]是上第i个台阶的方法数量
dp = [0] * (n+1)
#3.dp初始化
dp[0] = 1
dp[1] = 1
#4.遍历顺序(从前到后)
for i in range(2,n+1):
#2.递推公式
dp[i] = dp[i-1] + dp[i-2]
return dp[n]
746. 使用最小花费爬楼梯
解题思路:动态规划
class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
#1.dp[i] 到达第i个台阶的cost。 3.数组初始化
dp = [0] * (len(cost) + 1)
# dp[0] = 0
# dp[1] = 0
#4.遍历顺序(从前到后)
for i in range(2,len(cost)+1):
#2.递推公式
dp[i] = min(dp[i-1] + cost[i-1],dp[i-2]+cost[i-2])
return dp[-1]