class Solution {
//dp
//Let f(i, j) to be the number of distinct subsequences of T(j:) in S(i:). Consider the ith character in S. If we can use it to match T[j], namely S[i] == T[j], then
//1. f(i, j) = f(i+1, j+1).
//If we do not want use it in our matching, then
//2. f(i, j) = f(i+1, j). because every T[j] must be matched
//Thus,f(i, j) = f(i+1, j) + (S[i] == T[j]) * f(i+1, j+1).
// some tricks
//1. decompose it to dimension 1, and so i:(n,0]
//2. for the same j, we can not let T[j] affect f(i+1, j+1) then through f(i+1, j+1) affect f(i+1, j), so j:[0,n)
public:
int numDistinct(string S, string T) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> f(T.size()+1, 0);
f[T.size()] = 1;
for(int i = S.size()-1; i >= 0; i--)
{//decompose to one dimension
for(int j = 0; j < T.size(); ++j)
{
f[j] = f[j]+(S[i]==T[j])*f[j+1];
}
}
//
return f[0];
}
};
second time
class Solution {
public:
int numDistinct(string S, string T) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int len1 = S.size();
int len2 = T.size();
vector<vector<int> > f(len1+1, vector<int>(len2+1, 0));
for(int i = 0; i <= len1; ++i) f[i][0] = 1;
for(int i = 1; i <= len1; ++i)
{
for(int j = 1; j <= len2; ++j)
{
f[i][j] += f[i-1][j];
if(S[i-1] == T[j-1]) f[i][j] += f[i-1][j-1];
}
}
return f[len1][len2];
}
};