美文网首页LeetCode
115. 不同的子序列

115. 不同的子序列

作者: MarcQAQ | 来源:发表于2021-03-17 19:37 被阅读0次

给定一个字符串 s 和一个字符串 t ,计算在 s 的子序列中 t 出现的个数。
字符串的一个 子序列 是指,通过删除一些(也可以不删除)字符且不干扰剩余字符相对位置所组成的新字符串。(例如,"ACE" 是 "ABCDE" 的一个子序列,而 "AEC" 不是)
题目数据保证答案符合 32 位带符号整数范围。
输入:s = "rabbbit", t = "rabbit"
输出:3
解释:
如下图所示, 有 3 种可以从 s 中得到 "rabbit" 的方案。
(上箭头符号 ^ 表示选取的字母)
rabbbit
^^^^ ^^
rabbbit
^^ ^^^^
rabbbit
^^^ ^^^
采用DP,重点在于状态转移方程。令二维数组distinct_nums[][]distinct_nums[i][j]表示s[0...j]的子序列中t[0...i]出现的个数。我们可以这样来填充distinct_nums[][]。如果s[j]不等于t[i],那子串不可能以s[j]结尾,故distinct_nums[i][j] = distinct_nums[i][j - 1]。如果s[j]等于t[i],那则有两种情况,子串以s[j]结尾(distinct_nums[i - 1][j - 1])或者不以s[j]结尾(distinct_nums[i][j - 1])。总结下来:

distinct_nums[i][j] = distinct_nums[i - 1][j - 1] + distinct_nums[i][j - 1] if s[j] == t[i] else distinct_nums[i][j - 1]

时间空间复杂度均为O(s * t)

class Solution:
    def numDistinct(self, s: str, t: str) -> int:
        # cover the edge cases
        if t == '':
            return 1
        if s == '':
            return 0

        distinct_nums = list()
        for _ in range(len(t)):
            distinct_nums.append([0] * len(s))

        # initialise the first line
        for idx in range(len(s)):
            if s[idx] == t[0]:
                distinct_nums[0][idx] = (distinct_nums[0][idx - 1] + 1) if idx > 0 else 1
            else:
                distinct_nums[0][idx] = distinct_nums[0][idx - 1] if idx > 0 else 0

        # from left to right, top to down, fill the matrix
        for i in range(1, len(t)):
            for j in range(1, len(s)):
                distinct_nums[i][j] = distinct_nums[i][j - 1]
                if s[j] == t[i]:
                    distinct_nums[i][j] += distinct_nums[i - 1][j - 1]

        return distinct_nums[-1][-1]

相关文章

  • 115. 不同的子序列

    题目描述 distinct-subsequences 给定一个字符串 S 和一个字符串 T,计算在 S 的子序列中...

  • 115. 不同的子序列

    题目描述 给定一个字符串 S 和一个字符串 T,计算在 S 的子序列中 T 出现的个数。一个字符串的一个子序列是指...

  • 115. 不同的子序列

    给定一个字符串 S 和一个字符串 T,计算在 S 的子序列中 T 出现的个数。 一个字符串的一个子序列是指,通过删...

  • 115. 不同的子序列

    给定一个字符串 s 和一个字符串 t ,计算在 s 的子序列中 t 出现的个数。字符串的一个 子序列 是指,通过删...

  • LeetCode 115. 不同的子序列

    题目 给定一个字符串 s 和一个字符串 t ,计算在 s 的子序列中 t 出现的个数。字符串的一个 子序列 是指,...

  • leetcode 115. 不同的子序列 golang

    不同的子序列 思路 动态规划 dp[i][j]表示S前i个字符 中 T前j个字符的个数。 则有如下递推公式 如果 ...

  • LeetCode 力扣 115. 不同的子序列

    题目描述(困难难度) 给定两个字符串 S 和T,从 S 中选择字母,使得刚好和 T 相等,有多少种选法。 解法一 ...

  • python实现leetcode之115. 不同的子序列

    解题思路 使用缓存避免重复计算定义一个函数,计算s的某区间包含t的某区间多少次细节如代码中的注释 115. 不同的...

  • 不同的子序列

    给出字符串S和字符串T,计算S的不同的子序列中T出现的个数。 子序列字符串是原始字符串通过删除一些(或零个)产生的...

  • 不同的子序列

    dp存储该点含之前的所有子序列匹配的解个数。首先对第一列初始化,先确定第一个是否匹配然后再从第二位根据dp[0][...

网友评论

    本文标题:115. 不同的子序列

    本文链接:https://www.haomeiwen.com/subject/cywecltx.html