File tree 1 file changed +46
-0
lines changed
1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * DP bottom up
3
+ */
4
+ class Solution {
5
+ fun numDistinct (s : String , t : String ): Int {
6
+ val dp = Array (s.length + 1 ) { IntArray (t.length + 1 ) }
7
+
8
+ for (i in 0 .. s.length)
9
+ dp[i][t.length] = 1
10
+
11
+ for (i in s.length - 1 downTo 0 ) {
12
+ for (j in t.length - 1 downTo 0 ) {
13
+ if (s[i] == t[j])
14
+ dp[i][j] + = (dp[i + 1 ][j + 1 ] + dp[i + 1 ][j])
15
+ else
16
+ dp[i][j] + = dp[i + 1 ][j]
17
+ }
18
+ }
19
+
20
+ return dp[0 ][0 ]
21
+ }
22
+ }
23
+
24
+ /*
25
+ * DFS + Memoization
26
+ */
27
+ class Solution {
28
+ fun numDistinct (s : String , t : String ): Int {
29
+ val memo = Array (s.length) { IntArray (t.length) { - 1 } }
30
+
31
+ fun dfs (i : Int , j : Int ): Int {
32
+ if (j == t.length) return 1
33
+ if (i == s.length) return 0
34
+ if (memo[i][j] != - 1 ) return memo[i][j]
35
+
36
+ if (s[i] == t[j])
37
+ memo[i][j] = dfs(i + 1 , j + 1 ) + dfs(i + 1 , j)
38
+ else
39
+ memo[i][j] = dfs(i + 1 , j)
40
+
41
+ return memo[i][j]
42
+ }
43
+
44
+ return dfs(0 , 0 )
45
+ }
46
+ }
You can’t perform that action at this time.
0 commit comments