递归:只能过小数据
class Solution {
public:
int numDistinct(string S, string T) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int cnt = 0;
dfs(S, T, 0, 0, cnt);
return cnt;
}
void dfs(string &S, string &T, int indexS, int indexT, int &cnt)
{
if (indexT == T.size())
{
++cnt;
return;
}
for (int i = indexS; i < S.size(); ++i)
{
if (S[i] == T[indexT])
{
dfs(S, T, i + 1, indexT + 1, cnt);
}
}
}
};
下面是非递归的方法:
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, 0);
F[0] = 1;
for (int i = 0; i < S.size(); ++i)
for (int j = F.size() - 1; j >= 1; --j)
if (S[i] == T[j - 1])
F[j] += F[j - 1]; //选S[i]为F[j - 1]种,不选为F[j]种
return F[T.size()];
}
};