程式碼隨想錄演算法訓練營第天 |
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