目录
学习目标
学习内容
1143.最长公共子序列
1035.不相交的线
53. 最大子序和 动态规划
学习目标
- 1143.最长公共子序列
- 1035.不相交的线
- 53. 最大子序和 动态规划
学习内容
1143.最长公共子序列
1143. 最长公共子序列 - 力扣(LeetCode)https://leetcode.cn/problems/longest-common-subsequence/
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
n = len(text1)
m = len(text2)
dp = [[0]*(n+1)for _ in range(m+1)]
for i in range(1,m+1):
for j in range(1,n+1):
if text1[j-1]==text2[i-1]:
dp[i][j] = dp[i-1][j-1]+1
else:
dp[i][j]=max(dp[i][j-1],dp[i-1][j])
#print(dp)
return dp[-1][-1]
1035.不相交的线
1035. 不相交的线 - 力扣(LeetCode)https://leetcode.cn/problems/uncrossed-lines/
class Solution:
def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int:
# 相当于最大公共子序列(不连续)
# dp[i][j]表示text1[0:i-1]和text[0:j-1]的最长公共子序列
# 递推公式 if text1[i-1]==text2[j-1]: dp[i][j] = dp[i-1][j-1]+1 else dp[i][j] = max(dp[i-1][j],dp[i][j-1])
# 初始化 0
# 递推公式 从左到右 从上到下
n = len(nums1)
m = len(nums2)
dp = [[0]*(m+1)for _ in range(n+1)]
for i in range(1,n+1):
for j in range(1,m+1):
if nums1[i-1]==nums2[j-1]:
dp[i][j] = dp[i-1][j-1]+1
else:
dp[i][j] = max(dp[i-1][j],dp[i][j-1])
# print(dp)
return dp[-1][-1]
53. 最大子序和 动态规划
53. 最大子数组和 - 力扣(LeetCode)https://leetcode.cn/problems/maximum-subarray/
import math
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
n = len(nums)
if n==1:return nums[0]
dp = [[-math.inf]*(n)for _ in range(2)]
dp[1][0] = nums[0]
res = -math.inf
for i in range(1,n):
dp[0][1] = max(dp[0][i-1],dp[1][i-1])
dp[1][i] = max(0,dp[1][i-1])+nums[i]
res = max(res,dp[0][i],dp[1][i])
print(dp)
return res
import math
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
n = len(nums)
if n==1:return nums[0]
a = -math.inf
b = nums[0]
res = -math.inf
for i in range(1,n):
a = max(a,b)
b = max(0,b)+nums[i]
res = max(res,a,b)
return res