0
点赞
收藏
分享

微信扫一扫

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):
# space O(n^2)
def _numDistinct(self, s, t):
"""
:type s: str
:type t: str
:rtype: int
"""
dp = [[0] * (len(t) + 1) for _ in xrange(0, len(s) + 1)]

for i in xrange(0, len(s) + 1):
dp[i][0] = 1

for i in xrange(1, len(s) + 1):
for j in xrange(1, len(t) + 1):
dp[i][j] += dp[i - 1][j]
if t[j - 1] == s[i - 1]:
dp[i][j] += dp[i - 1][j - 1]

return dp[-1][-1]

def numDistinct(self, s, t):
"""
:type s: str
:type t: str
:rtype: int
"""
dp = [0] * (len(t) + 1)
for i in xrange(1, len(s) + 1):
pre = 1
for j in xrange(1, len(t) + 1):
tmp = dp[j]
if t[j - 1] == s[i - 1]:
dp[j] += pre
pre = tmp
return dp[-1]


举报

相关推荐

0 条评论