思路:计数问题往往用DP
class Solution {
public:
int numDistinct(string S, string T) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int> > f(S.size()+1, vector<int>(T.size()+1, 0));
for(int i = 0; i <= S.size(); ++i)
f[i][T.size()] = 1;
for(int i = S.size()-1; i >= 0; --i)
for(int j = T.size()-1; j >= 0; --j)
f[i][j] = f[i+1][j] + (S[i] == T[j])*f[i+1][j+1];
return f[0][0];
}
};
优化空间
class Solution {
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);
f[T.size()] = 1;
for(int i = S.size()-1; i >= 0; --i)
for(int j = 0; j < T.size(); ++j)
f[j] += (S[i] == T[j]) * f[j+1];
return f[0];
}
};