## Leetcode 115：不同的子序列（最详细的解法！！！）

``````输入: S = "rabbbit", T = "rabbit"

(上箭头符号 ^ 表示选取的字母)

rabbbit
^^^^ ^^
rabbbit
^^ ^^^^
rabbbit
^^^ ^^^
``````

``````输入: S = "babgbag", T = "bag"

(上箭头符号 ^ 表示选取的字母)

babgbag
^^ ^
babgbag
^^    ^
babgbag
^    ^^
babgbag
^  ^^
babgbag
^^^
``````

``````s_len, t_len, result = len(s), len(t), 0
if s_len < t_len:
return result

if s_len == t_len:
if s == t:
return 1
return result
``````

``````for i in combinations(s, t_len):
new_t = "".join(i)
if new_t == t:
result += 1
``````

``````  Ø r a b b b i t
Ø 1 1 1 1 1 1 1 1
r 0 1 1 1 1 1 1 1
a 0 0 1 1 1 1 1 1
b 0 0 0 1 2 3 3 3
b 0 0 0 0 1 3 3 3
i 0 0 0 0 0 0 3 3
t 0 0 0 0 0 0 0 3
``````

``````class Solution:
def numDistinct(self, s, t):
"""
:type s: str
:type t: str
:rtype: int
"""
s_len, t_len = len(s), len(t)
mem = [[0]*(s_len+1) for _ in range(t_len+1)]
for i in range(s_len+1):
mem[0][i] = 1

for i in range(t_len):
for j in range(s_len):
if s[j] == t[i]:
mem[i+1][j+1] = mem[i][j] + mem[i+1][j]
else:
mem[i+1][j+1] = mem[i+1][j]

return mem[-1][-1]
``````

``````r a b b i t
0 0 0 0 0 0 Ø
1 0 0 0 0 0 r
1 1 0 0 0 0 a
1 1 1 0 0 0 b
1 1 2 1 0 0 b
1 1 3 3 0 0 b
1 1 3 3 3 0 i
1 1 3 3 3 3 t
``````

``````class Solution:
def numDistinct(self, s, t):
"""
:type s: str
:type t: str
:rtype: int
"""
t_len = len(t)
mem = [1]+[0]*t_len
for s_c in s:
for i in range(t_len-1, -1, -1):
if t[i] == s_c:
mem[i+1] += mem[i]

return mem[-1]
``````

0条评论