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)]
            
        
        

 

posted @ 2017-08-05 17:42  爱简单的Paul  阅读(157)  评论(0编辑  收藏  举报