Given a string S and a string T, count the number of distinct subsequences ofS 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
.
解决方法:
用DP来解这道题比较好,dp[i][j]表示t的i个字符在j个字符中的匹配情况,最终结果其实就是dp[m][n]。
首先,当i时,dp[0][j] = 1。
当t[i] == s[j]时,匹配数是不包括j时的前一个已经匹配的结果加上不包含i和j的已经匹配的结果,即:dp[i+1][j+1] = dp[i][j] + dp[i+1][j];
当t[i] != s[j]时,匹配数就是不包括j时的前一个已经匹配的结果,即:dp[i+1][j+1] = dp[i+1][j];
代码:
int numDistinct(string s, string t) {
int m = t.size(), n = s.size();
vector<vector<int>> dp(m+1, vector<int>(n + 1, 0));
for(int j = 0; j <= n;j++){
dp[0][j] = 1;
}
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if (s[j] == t[i]){
dp[i+1][j+1] = dp[i][j] + dp[i+1][j];
}else{
dp[i+1][j+1] = dp[i+1][j];
}
}
}
return dp[m][n];
}