LeetCode之“动态规划”:Distinct Subsequences

时间:2023-03-09 04:11:43
LeetCode之“动态规划”:Distinct Subsequences

  题目链接

  题目要求:

  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.

  该题解析参考自LeetCode题解

  设状态为dp[i][j],表示T[0, j]在S[0, i]里出现的次数。首先,无论S[i]和T[j]是否相等,若不使用S[i],则dp[i][j]=dp[i-1][j];若S[i]=T[j],则可以使用S[i],此时dp[i][j]=dp[i-1][j]+dp[i-1][j-1]。

  代码如下:

 class Solution {
public:
int numDistinct(string s, string t) {
int szS = s.size();
int szT = t.size();
if(szS < szT)
return ; vector<vector<int> > dp(szS + , vector<int>(szT + , ));
for(int i = ; i < szS + ; i++)
dp[i][] = ; for(int i = ; i < szS + ; i++)
for(int j = ; j < szT + ; j++)
{
if(s[i-] != t[j-])
dp[i][j] = dp[i-][j];
else
dp[i][j] = dp[i-][j] + dp[i-][j-];
} return dp[szS][szT];
}
};