• 代码随想录算法训练营Day55 (Day 54休息) | 动态规划(15/17) LeetCode 392.判断子序列 115.不同的子序列


    继续子序列的练习!

    第一题

    392. Is Subsequence

    Given two strings s and t, return true if s is a subsequence of t, or false otherwise.

    subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).

    首先想到双指针的解法,复杂度为O(n),也能接受。不过既然在练习动态规划,就还是按照动态规划的思路去解。

    在确定递推公式的时候,首先要考虑如下两种操作,整理如下:

    • if (s[i - 1] == t[j - 1])
      • t中找到了一个字符在s中也出现了
    • if (s[i - 1] != t[j - 1])
      • 相当于t要删除元素,继续匹配

    if (s[i - 1] == t[j - 1]),那么dp[i][j] = dp[i - 1][j - 1] + 1;,因为找到了一个相同的字符,相同子序列长度自然要在dp[i-1][j-1]的基础上加1

    if (s[i - 1] != t[j - 1]),此时相当于t要删除元素,t如果把当前元素t[j - 1]删除,那么dp[i][j] 的数值就是 看s[i - 1]与 t[j - 2]的比较结果了,即:dp[i][j] = dp[i][j - 1];

    1. class Solution:
    2. def isSubsequence(self, s: str, t: str) -> bool:
    3. dp = [[0] * (len(t)+1) for _ in range(len(s)+1)]
    4. for i in range(1, len(s)+1):
    5. for j in range(1, len(t)+1):
    6. if s[i-1] == t[j-1]:
    7. dp[i][j] = dp[i-1][j-1] + 1
    8. else:
    9. dp[i][j] = dp[i][j-1]
    10. if dp[-1][-1] == len(s):
    11. return True
    12. return False

    第二题

    115. Distinct Subsequences

    Given two strings s and t, return the number of distinct subsequences of s which equals t.

    The test cases are generated so that the answer fits on a 32-bit signed integer.

    这道题双指针就没法做了,只能用动态规划。

    递推公式为:dp[i][j] = dp[i - 1][j];

    从递推公式dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]; 和 dp[i][j] = dp[i - 1][j]; 中可以看出dp[i][j] 是从上方和左上方推导而来,那么 dp[i][0] 和dp[0][j]是一定要初始化的。

    1. class Solution:
    2. def numDistinct(self, s: str, t: str) -> int:
    3. n1, n2 = len(s), len(t)
    4. if n1 < n2:
    5. return 0
    6. dp = [0 for _ in range(n2 + 1)]
    7. dp[0] = 1
    8. for i in range(1, n1 + 1):
    9. prev = dp.copy()
    10. end = i if i < n2 else n2
    11. for j in range(1, end + 1):
    12. if s[i - 1] == t[j - 1]:
    13. dp[j] = prev[j - 1] + prev[j]
    14. else:
    15. dp[j] = prev[j]
    16. return dp[-1]

  • 相关阅读:
    图解LeetCode——1710. 卡车上的最大单元数(难度:简单)
    【ansible】自动化运维ansible之playbook剧本编写与运行
    Java Applet基础
    2023年软件测试常见面试题
    PSO粒子群算法优化FS508E五轴飞行模拟转台技术方案
    SSM流程
    华为云云耀云服务器L实例评测|windows系统3389防爆破之安全加固教程
    痞子衡嵌入式:i.MXRT中FlexSPI外设不常用的读选通采样时钟源 - loopbackFromSckPad
    2022.08.08_每日一题
    代码随想录day56|583. 两个字符串的删除操作72. 编辑距离
  • 原文地址:https://blog.csdn.net/Hanzq1997/article/details/133132097