leetcode : Distinct Subsequences
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.
动态规划:
状态转移公式可以写成
if(T[m-1] == S[n-1])
ans[m][n] = ans[m-1][n-1] + ans[m-1][n]
else
ans[m][n] = ans[m-1][n]
5:确定边界显然所有的问题都可以由ans[i][1]递推得到。其中i = 1,2,3,4。。。。。
6.AC代码
class Solution {
public:
int numDistinct(string S, string T) {
vector<vector<int>> dp( S.size() + 1, vector<int>(T.size() + 1,0) );
int counts = 0;
for(int i = 1; i <= S.size(); ++i){
if(S[i - 1] == T[0]){
++counts;
}
dp[i][1] = counts;
}
for(int i = 2; i <= T.size(); ++i)
for(int j = i; j <= S.size(); ++j){
f(i,j,dp,S,T);
}
return dp[S.size()][T.size()];
}
void f(int n, int m, vector<vector<int>> &dp, string &S, string &T){
if(S[m - 1] == T[n - 1]){
dp[m][n] = dp[m - 1][n] + dp[m - 1][n - 1];
}else{
dp[m][n] = dp[m - 1][n];
}
}
};
浙公网安备 33010602011771号