Given a string S and a string T, count the number of distinct subsequences of S which equals T.
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).
Example 1:
Input: S = "rabbbit", T = "rabbit"
Output: 3
思路:
dp[i][j]代表s[0...i]与t[0...j]匹配数
dp[i][j]=dp[i-1][j] //if s[i]!=t[j]
dp[i][j]=dp[i-1][j]+dp[i-1][j-1] //if s[i]==t[j]
AC code
二维写法:
class Solution
{
public:
int numDistinct(string s, string t)
{
if (s.empty() || t.empty()|| s.length() < t.length())
return 0;
int ls = s.length(), lt = t.length();
vector<vector<long long> > dp(ls + 1, vector<long long>(lt + 1, 0));
dp[0][0] = 1;
for (int i = 0; i < ls; ++i)
dp[i][0] = 1;
for (int i = 1; i <= ls; ++i)
for (int j = 1; j <= lt; ++j)
{
dp[i][j] = dp[i - 1][j];
if (s[i-1] == t[j-1])
dp[i][j] += dp[i - 1][j - 1];
}
return dp[ls][lt];
}
};
一维优化:
class Solution
{
public:
int numDistinct(string s, string t)
{
int m = s.length(), n = t.length();
vector<long> dp(n + 1, 0);
dp[0] = 1;
for (int i = 1; i <= m; i++)
{
for (int j = n; j >= 1; j--)
{
if (s[i - 1] == t[j - 1])
{
dp[j] += dp[j - 1];
}
}
}
return dp[n];
}
};