标签:cpp alt detail .com bottom net 动态 pre com
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.
给两个字符串S和T, 求在字符串S中删除某些字符后得到T。问一共能有多少种删除方法?
这个题用常规方法超时。
得用动态规划,动态规划最基本的就是要找到动态规划方程。
首先记:dp[i][j] 为 从S[0..j-1]中删除某些字符后得 T[0...i-1]的不同删除方法数量。
动态规划方程为: dp[i][j] = dp[i][j-1] + (S[j-1]==T[i-1] ? dp[i-1][j-1] : 0);
class Solution {
public:
int numDistinct(string S, string T) {
int m = S.size();
int n = T.size();
if(m<n) return 0;
vector<vector<int> > dp(n+1, vector<int>(m+1, 0));
for(int i=0; i<m; ++i)
dp[0][i] = 1;
for(int i=1; i<=n; ++i){
for(int j=1; j<=m; ++j){
dp[i][j] = dp[i][j-1] + (S[j-1]==T[i-1] ? dp[i-1][j-1] : 0);
}
}
return dp[n][m];
}
};class Solution {
public:
int numDistinct(string S, string T) {
int m = S.size();
int n = T.size();
if(m<n) return 0;
vector<int> dp1(m+1, 1);
vector<int> dp2(m+1, 0);
for(int i=1; i<=n; ++i){
for(int j=1; j<=m; ++j){
dp2[j] = dp2[j-1] + (S[j-1]==T[i-1] ? dp1[j-1] : 0);
}
dp1.clear();
dp1 = dp2;
dp2[0] = 0;
}
return dp1[m];
}
};[LeetCode] Distinct Subsequences [29]
标签:cpp alt detail .com bottom net 动态 pre com
原文地址:http://www.cnblogs.com/zhchoutai/p/6714751.html