动态规划五部曲
- 确定dp数组(dp table)以及下标的含义
- 确定递推公式
- dp数组如何初始化
- 确定遍历顺序
- 举例推导dp数组
题目一:
class Solution(object):
def fib(self, n):
"""
:type n: int
:rtype: int
"""
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]
题目二
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
dp = [0] * (n+1)
if n == 1:
return 1
dp[0] = 0
dp[1] = 1
dp[2] = 2
for i in range(3,n+1):
dp[i]=dp[i-1]+dp[i-2]
return dp[n]
题目三
class Solution(object):
def minCostClimbingStairs(self, cost):
"""
:type cost: List[int]
:rtype: int
"""
n = len(cost)
dp= [0] * (n+1)
dp[0] = 0
dp[1] = 0
for i in range(2,n+1):
dp[i]= min(dp[i-2]+cost[i-2],dp[i-1]+cost[i-1])
print(dp[i])
return dp[n]