题目:
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
.
思路:
刚刚开始想到的是回溯法,但是实现之后发现过不了大数据。所以还是采用处理字符串匹配问题的神器:动态规划。可以用一个二维数组dp[i][j]表示S的前i个字符所包含的子字符串和T的前j个字符的匹配个数。此时可以分为两种情况:
1)s[i] != t[j],那么dp[i][j] = dp[i-1][j],即如果当前的字符串不相等,则dp[i][j]的值为s抛去第j-1个字符之后,所包含的子串匹配个数。
2)s[i] == t[j],那么dp[i][j]就可以继承dp[i-1][j-1]的值,再加上没有s[i-1]这个字符的值,即dp[i][j] = dp[i-1][j-1] + dp[i-1][j]。更简单的理解可以是:按照t[j-1]是和s[i-1]匹配还是和s[i-1]之前的字符匹配,可以将结果分为两类,即dp[i-1][j-1]和dp[i-1][j]。
另外初始状态dp[i][0] = 1,可以理解为空串是任意字符串的子串;而dp[0][j] = 0,可以理解为空串不能包含任意一个非空字符串。
代码:
class Solution {
public:
int numDistinct(string s, string t)
{
int s_size = s.length();
int t_size = t.length();
if(t_size > s_size || s_size == 0 || t_size == 0) {
return 0;
}
vector<vector<int>> dp(s_size + 1, vector<int>(t_size + 1, 0));
for(int i = 0; i <= s_size; ++i) {
for(int j = 0; j <= t_size; ++j) {
if (j == 0) { // t is an empty string
dp[i][j] = 1;
}
else if (i == 0) { // s is an empty string
dp[i][j] = 0;
}
else {
if(s[i-1] == t[j-1]) {
dp[i][j] += dp[i-1][j-1];
}
dp[i][j] += dp[i-1][j]; // discard the last character of s
}
}
}
return dp[s_size][t_size];
}
};