• Leetcode -- 115. Distinct Subsequences


    Given a string S and a string T, count the number of distinct subsequences of S which equals T.

    A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).

    Here is an example:
    S = "rabbbit", T = "rabbit"

    Return 3.

    class Solution(object):
        def numDistinct(self, s, t):
            """
            :type s: str
            :type t: str
            :rtype: int
            """
            # 关键是定义各个状态,找出状态转移方程
            # dp[i][j]表示字符串s[0~i-1] 中有多少个t[0~j-1].
            dp = [[0 for col in range(len(t) + 1)] for row in range(len(s) + 1)]
            if len(t) == 0 or len(s) == 0:
                return 0
            for i in range(len(s) + 1):     # 给第一列边界值赋值,此时为s[0],即为空时
                dp[i][0] = 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的维度要小1,所以为i-1,j-1
                        #如果S的第i个字符和T的第j个字符相同,那么所有dp[i-1][j-1]中满足的结果都会成为新的满足的序列
                        dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]
                    else:
                        #假设S的第i个字符和T的第j个字符不相同,那么就意味着dp[i][j]的值跟res[i-1][j]是一样
                        dp[i][j] = dp[i - 1][j]
            return dp[len(s)][len(t)]
                
            
            
  • 相关阅读:
    DS博客作业02--线性表
    DS博客作业01--日期抽象数据类型设计与实现
    C语言博客作业06--结构体&文件
    C语言博客作业05--指针
    C语言博客作业04--数组
    DS博客作业8——课程总结
    DS博客作业07——查找
    DS博客作业06--图
    DS博客作业——树
    DS博客作业03--栈和队列
  • 原文地址:https://www.cnblogs.com/simplepaul/p/7290905.html
Copyright © 2020-2023  润新知