Distinct Subsequences
Description
Given a string S and a string T, count the number of distinct subsequences of T in S.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).
Example Given S = "rabbbit", T = "rabbit", return 3.
Challenge:
Do it in O(n2) time and O(n) memory.
O(n2) memory is also acceptable if you do not know how to optimize memory.
Link
Method
- x
- x
Example
- 1
class Solution { public: /** * @param S, T: Two string. * @return: Count the number of distinct subsequences */ int numDistinct(string& s1, string& s2) { // write your code here if (s1.empty()) { return 0; } int n1 = s1.size(); int n2 = s2.size(); vector<vector<int>> dp(n1+1, vector<int>(n2+1, 0)); for (int i = 0; i <= n1; ++i) { dp[i][0] = 1; } for (int i = 1; i <= n1; ++i) { for (int j = 1; j <= n2; ++j) { dp[i][j] = dp[i-1][j]; if (s1[i-1] == s2[j-1]) { dp[i][j] += dp[i-1][j-1]; } // if the last letter is the same // dp[abcc][abc] = dp[abc][ab] + dp[abc][abc] // if (s1[i-1] == s2[j-1]) { // dp[i][j] = dp[i-1][j-1] + dp[i-1][j]; // } else { // // when s1[abcd] s2[abc] // // d != c => dp[abcd][abc] = dp[abc][abc] // dp[i][j] = dp[i-1][j]; // } } } return dp[n1][n2]; } };
Similar problems
x
Tags
x