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).
Here is an example:
S = "rabbbit"
, T = "rabbit"
Return 3
.
动态规划大法好。需要注意动态数组的初始化以及状态转移方程:
当S为空,T不为空时,S必然不包含T,dp[0][i]=0
当S不为空,T为空时,S必然包含T,dp[i][0] = 1
当S[i-1] == T[j-1]时,可以匹配该字符继续往下判断,也可以不匹配该字符继续往下判断,dp[i][j] = dp[i-1][j-1]+dp[i-1][j]
当S[i-1] != T[j-1]时,只能不匹配该字符继续往下判断,dp[i][j] = dp[i-1][j]
代码如下:
class Solution {
public:
int numDistinct(string s, string t) {
int m=s.size(),n=t.size();
int dp[m+1][n+1];
memset(dp,0,sizeof(int)*(m+1)*(n+1));
for(int i=0;i<=s.size();i++)
dp[i][0] = 1;
for(int i=1;i<m+1;i++)
{
for(int j=1;j<n+1;j++)
{
if(s[i-1] == t[j-1])
{
dp[i][j] = dp[i-1][j-1] + dp[i-1][j];
}
else
{
dp[i][j] = dp[i-1][j];
}
}
}
return dp[m][n];
}
};