Skip to content

Commit 21e4699

Browse files
committed
java: Created distinct subsequences
1 parent 5161ef7 commit 21e4699

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// Dynammic Programming - Memoization
2+
// Time Complexity O(s * t) | Space Complexity O(s * t)
3+
class Solution {
4+
public int numDistinct(String s, String t) {
5+
6+
int n = s.length() + 1;
7+
int m = t.length() + 1;
8+
int[][] memo = new int[n][m];
9+
10+
for (int[] row : memo){
11+
Arrays.fill(row, -1);
12+
}
13+
14+
return recursion(s, t, 0, 0, memo);
15+
16+
}
17+
18+
19+
public int recursion(String s, String t, int sIdx, int tIdx, int[][] memo){
20+
21+
if (memo[sIdx][tIdx] != -1){
22+
return memo[sIdx][tIdx];
23+
}
24+
25+
if (tIdx >= t.length()){
26+
return 1;
27+
}
28+
29+
if (sIdx >= s.length()){
30+
return 0;
31+
}
32+
33+
if (t.charAt(tIdx) == s.charAt(sIdx)){
34+
memo[sIdx][tIdx] = recursion(s, t, sIdx + 1, tIdx + 1, memo) + recursion(s, t, sIdx + 1, tIdx, memo);
35+
return memo[sIdx][tIdx];
36+
}
37+
38+
memo[sIdx][tIdx] = recursion(s, t, sIdx + 1, tIdx, memo);
39+
return memo[sIdx][tIdx];
40+
41+
}
42+
43+
}

0 commit comments

Comments
 (0)