力扣0115——不同的子序列

不同的子序列

难度:困难

题目描述

给你两个字符串 st ,统计并返回在 s子序列t 出现的个数,结果需要对 1 0 9 10^9 109 + 7 取模。

示例1

输入: s = “rabbbit”, t = “rabbit”
输出:3

示例2

输入: s = “babgbag”, t = “bag”
输出5

题解

根据题目可知,此题需要用到动态规划,动态规划方程为:
d p [ i ] [ j ] = { d p [ i − 1 ] [ j − 1 ] + d p [ i − 1 ] [ j ] , c1[i - 1] == c2[j - 1] d p [ i − 1 ] [ j ] , c1[i - 1] != c2[j - 1] dp[i][j] = \begin{cases} dp[i - 1][j - 1] + dp[i - 1][j],&\text{c1[i - 1] == c2[j - 1]} \\ dp[i - 1][j],&\text{c1[i - 1] != c2[j - 1]} \end{cases} dp[i][j]={dp[i1][j1]+dp[i1][j],dp[i1][j],c1[i - 1] == c2[j - 1]c1[i - 1] != c2[j - 1]
其中,c1为s中的字符,c2为t中的字符

想法代码

using System;


public class Solution
{
    public static void Main(string[] args)
    {
        string s = "babgbag";
        string t = "bag";
        Solution solution = new Solution();
        int ans = solution.NumDistinct(s, t);
        Console.WriteLine(ans);
    }

    public int NumDistinct(string s, string t)
    {
        int m = s.Length;
        int n = t.Length;
        if (m < n)
        {
            return 0;
        }

        int[,]dp = new int[m + 1, n + 1];
        for (int i = 0; i <= m; i++)
        {
            dp[i, 0] = 1;
        }

        for (int i = 1; i <= m; i++)
        {
            char c1 = s[i - 1];
            for (int j = 1; j <= n; j++)
            {
                char c2 = t[j - 1];
                if (c1 == c2)
                {
                    dp[i, j] = dp[i - 1, j - 1] + dp[i - 1, j];
                }
                else
                {
                    dp[i, j] = dp[i - 1, j];
                }
            }
        }

        return dp[m, n];
    }
}

你可能感兴趣的:(算法进修,leetcode,算法,职场和发展)