Problem
Given two strings s and t, return the number of distinct subsequences ofs that equal t.
A subsequence is formed by deleting some characters from a string without changing the relative order of the remaining characters.
Since the number of subsequences can be large, the result may require a large integer type.
Example(s)
Example 1
Input
s = "rabbbit"
t = "rabbit"
Output
3
Example 2
Input
s = "babgbag"
t = "bag"
Output
5
Solution
This problem can be solved using Dynamic Programming with Memoization. At each position ins, we have two choices: use the current character if it matches the current character in t, or skip it and move to the next character in s.
If
s[i] matches t[j], we can take that character and move both pointers forward. We can also skip the character from s and continue searching for another match.
If
j reaches the end of t, we have successfully formed the target string, so we return 1. If i reaches the end of s before t is formed, we return 0.
The result for each pair of positions
(i, j) is stored in the memo array to avoid recalculating the same subproblem.
class Solution {
public int numDistinct(String s, String t) {
Integer[][] memo = new Integer[s.length()][t.length()];
return numDistinct(s, t, 0, 0, memo);
}
public int numDistinct(String s, String t, int i, int j, Integer[][] memo) {
// t is fully matched, so we found one valid subsequence
if (j >= t.length())
return 1;
// s is exhausted before t is matched
if (i >= s.length())
return 0;
if (memo[i][j] != null)
return memo[i][j];
int take = 0;
// Take s[i] if it matches t[j]
if (s.charAt(i) == t.charAt(j)) {
take = numDistinct(s, t, i + 1, j + 1, memo);
}
// Skip s[i]
return memo[i][j] = take + numDistinct(s, t, i + 1, j, memo);
}
}
Complexity
There arem × n possible combinations of positions in s and t, and each state is calculated only once. Therefore, the time complexity is O(m × n).
The memoization array stores
m × n states, and the recursion stack can grow up to O(m). Therefore, the extra space complexity is O(m × n).
Comments
No comments yet. Ask a question or share what helped.