代码随想录44天
1143.最长公共子序列
class Solution:
def longestCommonSubsequence(self, s: str, t: str) -> int:
n, m = len(s), len(t)
@cache # 缓存装饰器,避免重复计算 dfs 的结果(记忆化)
def dfs(i: int, j: int) -> int:
if i < 0 or j < 0:
return 0
if s[i] == t[j]:
return dfs(i - 1, j - 1) + 1
return max(dfs(i - 1, j), dfs(i, j - 1))
return dfs(n - 1, m - 1)
1035.不相交的线
class Solution:
def maxUncrossedLines(self, s: List[int], t: List[int]) -> int:
n, m = len(s), len(t)
@cache # 缓存装饰器,避免重复计算 dfs 的结果(记忆化)
def dfs(i, j):
if i < 0 or j < 0:
return 0
if s[i] == t[j]:
return dfs(i - 1, j - 1) + 1
return max(dfs(i - 1, j), dfs(i, j - 1))
return dfs(n - 1, m - 1)
53. 最大子序和
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
size = len(nums)
if size == 0:
return 0
dp = [0 for _ in range(size)]
dp[0] = nums[0]
392.判断子序列
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
if not s: return True
i = 0
for c in t:
if s[i] == c:
i += 1
# 若已经遍历完 s ,则提前返回 true
if i == len(s):
return True
return False
原文地址:https://blog.csdn.net/weixin_43631425/article/details/144437738
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!