原题如下:
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
.
思路:这道题看似简单,实则比较复杂,因为首先想到的与人的思维相同的深度遍历的方法行不通,之后借鉴了大牛的解法,还是采用动态规划的思想,而且是二维动态规划的问题,以模式串T为行,以原串S为列构成二维矩阵,动态转移方程分两种情况,如果T[i] !=S[j],则vv[i][j]=vv[i][j-1],否则为vv[i][j]=vv[i][j-1]+vv[i-1][j-1].
class Solution {
public:
int numDistinct(string S, string T) {
int m = T.size();
int n = S.size();
if(m == 0 || n == 0){
return 0;
}
vector<vector<int>>vv(m);
for(int i = 0; i < m; i++){
vv[i] = vector<int>(n);
}
if(S[0] == T[0])
vv[0][0] = 1;
else
vv[0][0] = 0;
for(int j = 1; j < n; j++){
if(S[j] == T[0])
vv[0][j] = vv[0][j - 1] + 1;
else
vv[0][j] = vv[0][j - 1];
}
for(int i = 1; i < m; i++){
vv[i][0] = 0;
}
for(int i = 1; i < m; i++){
for(int j = 1; j < n; j++){
vv[i][j] = vv[i][j - 1];
if(T[i] == S[j]){
vv[i][j] +=vv[i - 1][j - 1];
}
}
}
return vv[m - 1][n - 1];
}
};