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).
Here is an example:
S = "rabbbit"
, T = "rabbit"
Return 3
.
代码如下:
class Solution {
public:
int numDistinct(string s, string t) {
if(t.size() > s.size())
return 0;
int count = 0;
countSubStr(s, t, 0, 0, &count);
return count;
}
void countSubStr(string& s, string& t, int sk, int tk, int* count)
{
if(sk == s.size() || tk == t.size())
{
if(tk == t.size())
(*count)++;
return;
}
if(s[sk] == t[tk])
{
countSubStr(s, t, sk+1, tk+1, count);
countSubStr(s, t, sk+1, tk, count);
}
else
countSubStr(s, t, sk+1, tk, count);
}
};
不幸超时,处理字符串的递归一般都超时,那就只能动态规划解决了。
此题为二维动态规划,构建 T.len * S.len 的二维数组 F ,初始化为0;F[i][j] 代表T[0]~T[i] 在 S[0]~[j]的子串个数
初始化 F[0][j],即 T 的第一个字符与 S 的匹配情况,如果 T[0] == S[j] 则 F[0][j] = 1,T[0] 后面的字符匹配均要根据 T 中上一字符的匹配情况而定,匹配到 T[i] 和 S[j] 时,如果两个字符相等,那么F[i][j] 为 F[i-1][1]、F[i-1][2]、...、F[i-1][j-1] 的和,(可以画二维图理解)
公式如下:
F[i-1][1]+F[i-1][2]+...+F[i-1][j-1] ; (T[i] == S[j])
F[i][j] = {
0; (T[i] != S[j])
代码如下:
class Solution {
public:
int numDistinct(string s, string t) {
if(t.size() > s.size())
return 0;
int slen = s.length(), tlen = t.length();
int result = 0;
vector<vector<int> > F(tlen, vector<int>(slen, 0));
for(int j=0; j<slen; ++j)
if(t[0] == s[j])
F[0][j] = 1;
for(int i=1; i<tlen; ++i)
{
for(int j=1; j<slen; ++j)
{
if(t[i] == s[j])
{
for(int h=0; h<j; ++h)
F[i][j] += F[i-1][h];
}
}
}
for(int j=0; j<slen; ++j)
result += F[tlen-1][j];
return result;
}
};