训练营day55|动态规划|392.判断子序列、115.不同的子序列
392.判断子序列
要点
和最长公共子序列类似的思想
代码
class Solution:def isSubsequence(self, s: str, t: str) -> bool:m = len(s) + 1n = len(t) + 1dp = [[False] * n for _ in range(m)]for i in range(n):dp[0][i] = Truefor i in range(1, m):for j in range(i, n):if dp[i][j - 1] or (s[i - 1] == t[j - 1] and dp[i - 1][j - 1]):dp[i][j] = Truereturn dp[-1][-1]
class Solution:def isSubsequence(self, s: str, t: str) -> bool:m = len(s) + 1n = len(t) + 1dp = [[0] * n for _ in range(m)]for i in range(1, m):for j in range(i, n):if s[i - 1] == t[j - 1]:dp[i][j] = dp[i - 1][j - 1] + 1else:dp[i][j] = dp[i][j - 1]return (m - 1) == dp[-1][-1]
115.不同的子序列
要点
dp[i][j]:以i-1为结尾的s子序列中出现以j-1为结尾的t的个数为dp[i][j]。 初始化中dp[i][0] = 1
代码
class Solution:def numDistinct(self, s: str, t: str) -> int:m = len(s) + 1n = len(t) + 1dp = [[0] * n for _ in range(m)]for i in range(m):dp[i][0] = 1for i in range(1, m):for j in range(1, n):if s[i - 1] == t[j - 1]:dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]else:dp[i][j] = dp[i -1][j]return dp[-1][-1]