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

继续子序列的练习!

第一题

392. Is Subsequence

Given two strings s and t, return trueif sis a subsequence of t, or falseotherwise.

A 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 "++a++ b++c++ d++e++" while "aec" is not).

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

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

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

if (si - 1 == tj - 1),那么dpij = dpi - 1j - 1 + 1;,因为找到了一个相同的字符,相同子序列长度自然要在dpi-1j-1的基础上加1

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

python 复制代码
class Solution:
    def isSubsequence(self, s: str, t: str) -> bool:
        dp = [[0] * (len(t)+1) for _ in range(len(s)+1)]
        for i in range(1, len(s)+1):
            for j in range(1, len(t)+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[-1][-1] == len(s):
            return True
        return False

第二题

115. Distinct Subsequences

Given two strings s and t, return the number of distinct subsequences of swhich equalst.

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

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

递推公式为:dpij = dpi - 1j;

从递推公式dpij = dpi - 1j - 1 + dpi - 1j; 和 dpij = dpi - 1j; 中可以看出dpij 是从上方和左上方推导而来,那么 dpi0 和dp0j是一定要初始化的。

python 复制代码
class Solution:
    def numDistinct(self, s: str, t: str) -> int:
        n1, n2 = len(s), len(t)
        if n1 < n2:
            return 0

        dp = [0 for _ in range(n2 + 1)]
        dp[0] = 1

        for i in range(1, n1 + 1):

            prev = dp.copy()
            end = i if i < n2 else n2
            for j in range(1, end + 1):
                if s[i - 1] == t[j - 1]:
                    dp[j] = prev[j - 1] + prev[j]
                else:
                    dp[j] = prev[j]
        return dp[-1]
相关推荐
玛卡巴卡ldf25 分钟前
【LeetCode 手撕算法】(细节知识点总结)
java·数据结构·算法·leetcode·力扣
wanzehongsheng1 小时前
零碳产业园光伏园区光伏电站追踪对比固定:发电增益技术边界分析
算法·光伏发电·光伏·零碳园区·太阳能追光·低碳环保·追踪电站
KobeSacre1 小时前
CyclicBarrier 源码
java·jvm·算法
手写码匠1 小时前
注意力机制全家桶:从 Multi-Head 到 GQA 再到 Flash Attention 的手写实现
人工智能·深度学习·算法·aigc
学究天人2 小时前
数学公理体系大全:Comprehensive Collection of Mathematical Axiom Systems(卷3.2)
线性代数·算法·机器学习·数学建模·动态规划·抽象代数·拓扑学
tkevinjd2 小时前
力扣322-零钱兑换
算法·leetcode·动态规划
大鱼>2 小时前
AI+资产监控:农业设施智能监控系统
人工智能·深度学习·算法·机器学习
AI科技星2 小时前
乖乖数学·全域超复数统一场论:五大核心门槛与全套标准定量数据
人工智能·python·算法·金融·全域数学
学究天人3 小时前
数学公理体系大全:Comprehensive Collection of Mathematical Axiom Systems(卷1)
线性代数·机器学习·数学建模·动态规划·图论·抽象代数·傅立叶分析
Frostnova丶3 小时前
(13)LeetCode 53. 最大子数组和
算法·leetcode·职场和发展