目录
理论基础
动态规划五部曲:
1. 确定dp数组(dp table)以及下标的含义
2. 确定递推公式
3. dp数组如何初始化
4. 确定遍历顺序
5. 举例推导dp数组
509.斐波那契数
class Solution:
def fib(self, n: int) -> int:
if n < 2:
return n
a, b, sum = 0, 1, 0
for i in range(n-1):
sum = a + b
a, b = b, sum
return sum
70.爬楼梯
class Solution:
def climbStairs(self, n: int) -> int:
if n <= 2:
return n
dp1 = 1
dp2 = 2
for i in range(n-2):
tmp = dp1 + dp2
dp1, dp2 = dp2, tmp
return tmp
746.使用最小花费爬楼梯
class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
dp = [0,0] #dp[0]和dp[1]是0
for i in range(2, len(cost)+1):
dp.append(min(dp[i-2] + cost[i-2], dp[i-1] + cost[i-1]))
return dp[-1]