2
// We assume that dp[i][j] gives us the total number of distinct subsequences for the string s[03
// to i] which equals string t[0 to j]4
int f(int i, int j, String s, String t, int dp[][]) {5
// If t gets exhausted then all the characters in t have been matched with s so we can return 16
// (we found a subsequence)8
// if s gets exhausted then there are characters remaining in t which are yet to be matched as s9
// got exhausted they could not be matched so there is no distinct subsequence13
if (dp[i][j] != -1) return dp[i][j];14
// If both the characters in s[i] and t[j] match then we have two case15
// 1) Either consider the i'th character of s and find the remaining distinct subsequences of16
// s[0 to i-1] which equals t[0 to j-1] set i.e. f(i-1,j-1)17
// 2) Do not consider s[i] so we are still at the same j'th character of t as we had not been18
// considering s[i] matched with t[j] we check distinct subsequences of t[0 to j] in s[0 to i-1]20
if (s.charAt(i) == t.charAt(j)) {21
dp[i][j] = f(i - 1, j - 1, s, t, dp) + f(i - 1, j, s, t, dp);23
// If both of them do not match then we consider the 2nd case of matching characters25
dp[i][j] = f(i - 1, j, s, t, dp);30
public int numDistinct(String s, String t) {33
int dp[][] = new int[n][m];34
for (int i = 0; i < n; i++) {35
Arrays.fill(dp[i], -1);37
return f(n - 1, m - 1, s, t, dp);