File tree Expand file tree Collapse file tree 2 files changed +39
-0
lines changed
leetcode.com 115. Distinct Subsequences Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ from typing import List
2
+
3
+
4
+ class Solution :
5
+ def numDistinct (self , s : str , t : str ) -> int :
6
+ s = ' ' + s
7
+ t = ' ' + t
8
+ l_s = len (s )
9
+ l_t = len (t )
10
+ dp : List [List [int ]] = [[[- 1 , 0 ] for _ in range (len (s ))] for _ in range (len (t ))]
11
+ dp [0 ][0 ][0 ] = 0 # s의 0~c인덱스까지, t의 0~r인덱스까지 비교하여, match된 distinct subsequence 임을 뜻함
12
+ dp [0 ][0 ][1 ] = 1 # s의 0~c인덱스까지, t의 0~r인덱스까지 비교하여, match된 distinct subsequence 의 개수
13
+
14
+ answer = 0
15
+
16
+ for r in range (1 , l_t ):
17
+ for c in range (r , l_s - (l_t - r - 1 )):
18
+ if t [r ] == s [c ]:
19
+ for b in range (r - 1 , c ):
20
+ if dp [r - 1 ][b ][0 ] == r - 1 :
21
+ dp [r ][c ][0 ] = r
22
+ dp [r ][c ][1 ] += dp [r - 1 ][b ][1 ]
23
+
24
+ if dp [r ][c ][0 ] == l_t - 1 :
25
+ answer += dp [r - 1 ][b ][1 ]
26
+
27
+ return answer
Original file line number Diff line number Diff line change
1
+ from unittest import TestCase
2
+ from main import Solution
3
+
4
+
5
+ class TestSolution (TestCase ):
6
+ def test1_num_distinct (self ):
7
+ sol = Solution ()
8
+ self .assertEqual (3 , sol .numDistinct (s = "rabbbit" , t = "rabbit" ))
9
+
10
+ def test2_num_distinct (self ):
11
+ sol = Solution ()
12
+ self .assertEqual (5 , sol .numDistinct (s = "babgbag" , t = "bag" ))
You can’t perform that action at this time.
0 commit comments