一、知识点
动态规划五部曲
1.确定dp数组以及其下标的含义
2.确定递推公式
3.确定dp数组的初始化
4.确定遍历顺序
5.举例推导dp数组
二、例题
1.最大子数组和
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
opt=[nums[0]]
for i in nums[1:]:
opt.append(max(opt[-1]+i,i))
return max(opt)
2.最长公共子序列
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
len1,len2=len(text1),len(text2)
opt=[[0 for j in range(len2+1)] for i in range(len1+1)]
for i in range(len1):
for j in range(len2):
if text1[i]==text2[j]:
opt[i+1][j+1]=opt[i][j]+1
else:
opt[i+1][j+1]=max(opt[i+1][j],opt[i][j+1])
return opt[len1][len2]
3.买卖股票的最佳时机
class Solution:
def maxProfit(self, prices: List[int]) -> int:
min_in=prices[0]
max_out=0
for i in range(1,len(prices)):
min_in=min(prices[i],min_in)
max_out=max(prices[i]-min_in,max_out)
return max_out
4.买卖股票的最佳时机 II
两种解法:1.dp 2.贪心
class Solution:
def maxProfit(self, prices: List[int]) -> int:
# dp=[[0,0] for _ in range(len(prices))]
# dp[0][0],dp[0][1]=0,-prices[0]
# for i in range(1,len(prices)):
# dp[i][0]=max(dp[i-1][0],dp[i-1][1]+prices[i])
# dp[i][1]=max(dp[i-1][1],dp[i-1][0]-prices[i])
# return dp[len(prices)-1][0]
ans=0
for i in range(len(prices)-1):
ans+=max(0,prices[i+1]-prices[i])
return ans
5.最长回文子序列
class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
n=len(s)
dp = [[0]*n for _ in range(n)]
for i in range(n):
dp[i][i]=1
for i in range(n-1,-1,-1):
for j in range(i+1,n):
if s[i]==s[j]:
dp[i][j]=dp[i+1][j-1]+2
else:
dp[i][j]=max(dp[i+1][j],dp[i][j-1])
return dp[0][-1]