We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 0544b80 commit 0c18ac8Copy full SHA for 0c18ac8
1 file changed
distinct_subsequences.py
@@ -0,0 +1,27 @@
1
+class Solution:
2
+ # @param S, T: Two string.
3
+ # @return: Count the number of distinct subsequences
4
+ def numDistinct(self, S, T):
5
+ # write your code here
6
+ '''
7
+ 根据题目提供的例子,建一张二维表:
8
+ r a b b b i t (S)
9
+ r 0 1 1 1 1 1 1 1
10
+ a 0 0 1 1 1 1 1 1
11
+ b 0 0 0 1 2 3 3 3
12
+ b 0 0 0 0 1 3 3 3 # 关键在第一个3
13
+ i 0 0 0 0 0 0 3 3
14
+ t 0 0 0 0 0 0 0 3
15
+ (T)
16
+ dp[i][j] = dp[i][j - 1] + (T[i - 1] == S[j - 1] ? dp[i - 1][j - 1] : 0)
17
18
+ rows = len(T) + 1
19
+ cols = len(S) + 1
20
+ caches = [[0] * cols for i in xrange(rows)]
21
+ caches[0] = [1] * cols
22
+ for i in xrange(1, rows):
23
+ for j in xrange(1, cols):
24
+ caches[i][j] = caches[i][j - 1]
25
+ if T[i - 1] == S[j - 1]:
26
+ caches[i][j] += caches[i - 1][j - 1]
27
+ return caches[-1][-1]
0 commit comments