Skip to content

Commit c6c18fc

Browse files
committed
Add an alternative solution
1 parent 23ee149 commit c6c18fc

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

Distinct Subsequences.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,17 @@
11
class Solution:
2+
def numDistinct(self, S, T):
3+
n, m = len(S), len(T)
4+
f = [0] * (m + 1)
5+
f[0] = 1
6+
for i in xrange(n):
7+
for j in xrange(m - 1, -1, -1):
8+
if S[i] == T[j]:
9+
f[j + 1] += f[j]
10+
return f[m]
11+
12+
class Solution:
13+
''' The alternative solution is to use a 2D array.
14+
'''
215
def numDistinct(self, S, T):
316
ways = [[0 for j in range(len(S) + 1)] for i in range(len(T) + 1)]
417
for i in range(len(S) + 1):
@@ -8,4 +21,4 @@ def numDistinct(self, S, T):
821
ways[i][j] = ways[i][j - 1]
922
if T[i - 1] == S[j - 1]:
1023
ways[i][j] += ways[i - 1][j - 1]
11-
return ways[len(T)][len(S)]
24+
return ways[len(T)][len(S)]

0 commit comments

Comments
 (0)