代码随想录算法训练营第天 |
1143.最长公共子序列
https://leetcode.cn/problems/longest-common-subsequence/description/
代码随想录
https://programmercarl.com/1143.最长公共子序列.html#算法公开课
1035.不相交的线
https://leetcode.cn/problems/uncrossed-lines/description/
代码随想录
https://programmercarl.com/1035.不相交的线.html#其他语言版本
53.最大子序和
https://leetcode.cn/problems/maximum-subarray/description/
代码随想录
https://programmercarl.com/0053.最大子序和(动态规划).html#其他语言版本
392.判断子序列
https://leetcode.cn/problems/is-subsequence/submissions/549842019/
代码随想录
https://programmercarl.com/0392.判断子序列.html#算法公开课
1143.最长公共子序列
题解
- dp[i][j]:第i-1个text1和j-1个text2字符串的最长公共子序列;
- 初始化 dp = m+1 * n+1 的0矩阵;
- 递推:
- 字符串一致时:
dp[i][j] = dp[i-1][j-1]+1 - 字符串不一致时:
dp[i][j] = max(dp[i-1][j],dp[i][j-1])
- 字符串一致时:
点击查看代码
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
m = len(text1)
n = 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[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])
return dp[-1][-1]
1035. 不相交的线
题解
- 从逻辑上来讲和最长公共子序列一致
- 直接套的结果是一样的
点击查看代码
class Solution:
def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int:
m = len(nums1)
n = len(nums2)
dp = [[0]*(n+1) for _ in range(m+1)]
res = 0
for i in range(1,m+1):
for j in range(1,n+1):
if nums1[i-1]==nums2[j-1]:
dp[i][j] = dp[i-1][j-1]+1
else:
dp[i][j] = max(dp[i][j-1],dp[i-1][j])
return dp[-1][-1]
53. 最大子数组和
- dp:第i个字符串之前最大的连续和;
- 初始化:最小是第一个数;dp[0] = nums[0]; res = nums[0]
- 递推:
- dp[i] = max(dp[i-1]+nums[i],nums[i])
点击查看代码
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
dp = [0]*len(nums)
dp[0] = nums[0]
res = dp[0]
for i in range(1,len(nums)):
dp[i] = max(dp[i-1]+nums[i],nums[i])
if dp[i]>res:
res = dp[i]
return res
392.判断子序列
题解代码
- dp[i][j]:第i-1个s字符串和j-1个t字符串的相同字符串长度;
- 初始化:为了不用初始化第一行、第一列:dp[i][j]
- 递推:
- 如果s[i-1] == t[j-1] dp[i][j]=dp[i-1][j-1]+1
- 如果s[i-1]!=t[j-1] dp[i][j] = dp[i][j-1] 跳过t的这个点即可
- 如果dp[i][j]长度和s长度一样 说明符合要求;
点击查看代码
import numpy as np
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
m = len(s)
n = len(t)
dp = [[0] * (n+1) for _ in range(m+1)]
for i in range(1,m+1):
for j in range(1,n+1):
if s[i-1] == t[j-1]:
dp[i][j] = dp[i-1][j-1]+1
else:
dp[i][j] = dp[i][j-1]
if dp[i][j]>=m:
return True
if dp[-1][-1]>=m:
return True
else:
return False