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
.
1:注意特殊情況;2:設置二維數組保存個數;3:如果T是空串,則返回1;4:動態規劃獲得相應的個數
int numDistinct(string S, string T)
{
if(T.size() == 0)
{
return 1;
}
if(S.size() == 0 || T.size() > S.size())
{
return 0;
}
int rows = (int)T.length() + 1;
int columns = (int)S.length() + 1;
vector<vector<int> > result(rows, vector<int>(columns, 0));
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < columns; j++)
{
if(i == 0)
{
result[i][j] = 1;
}
else if(j == 0)
{
result[i][j] = 0;
}
else
{
result[i][j] = result[i][j-1];
if(T[i-1] == S[j-1])
{
result[i][j] += result[i-1][j-1];
}
}
}
}
return result[rows-1][columns-1];
}