115 Distinct Subsequences
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. (i.e., "ACE" is a subsequence of "ABCDE" while "AEC" is not).
Here is an example:
S = "rabbbit", T = "rabbit"
Return 3.
Solution
class Solution {
public:
int numDistinct(string s, string t) {
int ns = s.size(), nt = t.size();
if ( nt > ns ) return false;
vector<int> res1(ns, 0), res2(ns, 0);
if ( s[0] == t[0] ) res1[0] = 1;
for ( int i = 1; i <= ns-1; i++ ) {
if ( t[0] == s[i] ) res1[i] = res1[i-1]+1;
else res1[i] = res1[i-1];
}
for ( int i = 1; i <= nt-1; i++ ) {
res2[i-1] = 0;
for ( int j = i; j <= ns-1; j++ ) {
if ( t[i] != s[j] ) res2[j] = res2[j-1];
else res2[j] = res1[j-1] + res2[j-1];
}
swap(res1, res2);
}
return res1[ns-1];
}
};
notes: Dynamic programming.
// Relation between res[i][j], res[i-1][j-1] and res[i][j-1].
a a b b
a 1 2 2 2
b 0 0 2 4
if ( s[i] == t[j] )
res[i][j] = res[i-1][j-1] + res[i][j-1];
if ( s[i] != t[j] )
res[i][j] = res[i][j-1];