lc 115. Distinct Subsequences

https://leetcode.com/problems/distinct-subsequences/description/

 

求串s中有几个字串t?

 

开始看成了s和t有几个公共字串,想来也是dp。题目中明显s和t不是对称的。

 

对于s中最后字符c,如果和t中最后一个不同,那么去掉这个c是对结果无影响的。

如果相同,我们有两种选择:用它,不用它。

于是就是:

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

code:
class Solution:
    def update(self,i,j):
        if i<0 or j<0:
            return 0

    def numDistinct(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: int
        """
        sl=len(s)
        tl=len(t)
        if sl*tl==0:
            return 0
        dp=[[0]*tl for _ in range(sl)]
        if s[0]==t[0]:
            dp[0][0]=1
        for i in range(1,sl):
            dp[i][0]=dp[i-1][0]
            if s[i]==t[0]:
                dp[i][0]+=1
        for i in range(1,sl):
            for j in range(1,tl):
                if s[i]==t[j]:
                    dp[i][j]=dp[i-1][j-1]+dp[i-1][j]
                else:
                    dp[i][j] = dp[i - 1][j]
        # print(dp)
        return dp[-1][-1]
s=Solution()
print(s.numDistinct("babgbag", "bag"))
# print(s.numDistinct("rabbbit", "rabbit"))

 

posted @ 2018-09-20 01:00  Cloud.9  阅读(135)  评论(0编辑  收藏  举报