-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathDistinctSubsequences.java
More file actions
32 lines (31 loc) · 974 Bytes
/
DistinctSubsequences.java
File metadata and controls
32 lines (31 loc) · 974 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class Solution {
public int numDistinct(String S, String T) {
// Start typing your Java solution below
// DO NOT write main() function
int m = T.length(), n = S.length();
int[] f = new int[m + 1];
f[0] = 1;
for (int i = 1; i <= n; ++i) {
for (int j = m; j >= 1; --j) {
f[j] += (T.charAt(j - 1) == S.charAt(i - 1))
? f[j - 1] : 0;
}
}
return f[m];
}
}
public class Solution {
public int numDistinct(String s, String t) {
int m = s.length(), n = t.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 0; i <= m; ++i) {
dp[i][0] = 1;
}
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
dp[i][j] = dp[i - 1][j] + (s.charAt(i - 1) == t.charAt(j - 1) ? dp[i - 1][j - 1] : 0);
}
}
return dp[m][n];
}
}