描述
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.
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.
#include<iostream>
#include<string>
using namespace std;
int DistinctSubsequences(string S, string T)//二维DP
{
int len1 = S.size();
int len2 = T.size();
if (len2 > len1)
return 0;
int **p = new int*[len1 + 1];
for (int i = 0; i <= len1; i++)
p[i] = new int[len2 + 1];
for (int i = 0; i <= len1; i++)//初始化二维数组
{
for (int j = 0; j <= len2; j++)
{
if (j == 0)
p[i][j] = 1;
else
p[i][j] = 0;
}
}
for (int i = 1; i <= len1; i++)
{
for (int j = 1; j <= len2; j++)
{
if (S[i - 1] == T[j - 1])
p[i][j] = p[i - 1][j - 1] + p[i - 1][j];
else
p[i][j] = p[i - 1][j];
}
}
int res = p[len1][len2];
for (int i = 0; i <= len1; i++)
delete[]p[i];
delete[]p;
return res;
}
int main()
{
string S = "rabbbit";
string T = "rabbit";
int res = DistinctSubsequences(S, T);
cout << res << endl;
}