代码随想录算法训练营|五十三天

判断子序列

392. 判断子序列 - 力扣(LeetCode)

过程:

cs 复制代码
public class Solution {
    public bool IsSubsequence(string s, string t) {
        int[,] dp = new int[s.Length + 1, t.Length + 1];
        for (int i = 1; i <= s.Length; i++) {
            for (int j = 1; j <= t.Length; j++) {
                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[s.Length, t.Length] == s.Length) return true;
        return false;
    }
}

不同的子序列

115. 不同的子序列 - 力扣(LeetCode)

这里递推公式中,有相等和不相等两种情况,相等字符是dpi,j = dpi-1,j-1+dpi-1,j,例如下图的s和t字符串,循环到最后一个c时,dpi-1,j-1是首次遇到的次数,dpi-1,j是在此的循环之前所累计的次数,两个相加就是循环到最后一个c时所有的累计结果。如果不相等,就不需要考虑dpi-1,j-1

cs 复制代码
public class Solution {
    public int NumDistinct(string s, string t) {
        int[,] dp = new int[s.Length+1,t.Length+1];
        for(int i=0;i<=s.Length;i++)dp[i,0] = 1;
        for(int j=1;j<=t.Length;j++)dp[0,j] = 0;

        for(int i=1;i<=s.Length;i++){
            for(int j=1;j<=t.Length;j++){
                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[s.Length,t.Length];
    }
}
相关推荐
圣保罗的大教堂8 小时前
leetcode 3524. 求出数组的 X 值 I 中等
leetcode
Zane19948 小时前
暴力字符串匹配失配就要把文本指针往回拉,KMP凭什么能让它一直往前走
算法
Tim_109 小时前
【LeetCode】338、比特位计数
c++·算法·leetcode
木子算法9 小时前
不是重心也不是中点:费马—韦伯点、它的最优性条件与迭代求解
人工智能·算法·目标跟踪
tryxr10 小时前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_310 小时前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
Selvaggia10 小时前
DMD(Distribution Matching Distillation,分布匹配蒸馏)
算法
Navigator_Z11 小时前
LeetCode //C - 1255. Maximum Score Words Formed by Letters
c语言·算法·leetcode
All for pursuit.11 小时前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
开开心心就好11 小时前
安卓手写文字生成工具,多种纸张一直免费
网络·网络协议·tcp/ip·leetcode·智能手机·电脑·模拟退火算法