可以用动态规划来解决。
dp[i][j] 表示S中前i个到T中前j个有多少种解法。我们考虑新来了一个元素在i中,如果
S[i] != T[j]则应该删除它才有可能成功,所以此时
dp[i][j]=dp[i−1][j]
如果S[i] == T[i][j]则可以考虑删或者不删,删了的话则有和上一样的公式,如果不删则是固定S的i和S的j这种考虑,所以为dp[i-1][j-1]。所以有:
dp[i][j]=dp[i−1][j]+dp[i−1][j−1]
class Solution {
public:
/**
* @param S, T: Two string.
* @return: Count the number of distinct subsequences
*/
int numDistinct(string &S, string &T) {
// write your code here
vector<vector<int>> dp(S.length()+1,vector<int>(T.length()+1));
for(int i = 0; i < S.length()+1; ++i){
dp[i][0] = 1;
}
for(int i = 1; i < T.length()+1; ++i){
dp[0][i] = 0;
}
for(int i = 1; i < S.length()+1; ++i){
for(int j = 1; j < T.length()+1; ++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[S.length()][T.length()];
}
};
注意由于我们加入了空集这样的边界条件(这样其实很棒~如下图),所以遍历从下标 1 开始,所以判断的时候是s[i-1] T[j-1]。
有注意到状态j只和状态j-1有关系,可以用滚动数组~改成:
class Solution {
public:
/**
* @param S, T: Two string.
* @return: Count the number of distinct subsequences
*/
int numDistinct(string &S, string &T) {
// write your code here
vector<int> res(T.size()+1,0);
res[0] = 1;
for(int i = 1; i < S.size()+1; ++i){
int pre = 1;
for(int j = 1; j < T.size()+1; ++j){
int temp = res[j];
if(S[i-1] == T[j-1]) res[j] += pre;
pre = temp;
}
}
return res[T.size()];
}
};