Distinct Subsequences
Given a stringSand a stringT, count the number of distinct subsequences ofTinS.
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"
Return3
.
动态规划法活用总结:
1 二维表:很多问题都可以转化为二维表
2 三维表:比较难理解,时间效率一般是O(n*n*n)
3 二维表变一维表:一般是简化二维表,不需要保存整个表
4 一维表变常量:一般是由一维表简化而来,一维表也不需要保存,只保存当前结果和当前结果需要用的变量就可以
5 逆向填表:根据表进一步抽象简化出来,可以让程序更加简洁,当然也更加更加难理解。
设计动态规划法算法,应该循序渐进,先设计二维表或三维表,然后再简化,进一步优化,再简化,不要一步就写最简化的程序。
熟练之后,可以直接设计表,根据表特征,翻译为程序。
熟练递归回溯法有助于动态规划法的深入理解。
//最好理解的二维动态规划法,一次性ac。
int numDistinct2(string S, string T)
{
vector<vector<int> > ta(T.size()+1, vector<int>(S.size()+1));
for (int i = 0; i <= S.size(); i++)
{
ta[0][i] = 1;
}
for (int i = 1; i <= T.size(); i++)
{
for (int j = 1; j <= S.size(); j++)
{
if (T[i-1] == S[j-1]) ta[i][j] = ta[i][j-1] + ta[i-1][j-1];
else ta[i][j] = ta[i][j-1];
}
}
return ta[T.size()][S.size()];
}
//转置行和列的1维表动态规划法-优化
int numDistinct(string S, string T)
{
vector<int> ta(T.size()+1);
int a = 0, b = 1;
for (int i = 1; i <= S.size(); i++)
{
b = 1;
for (int j = 1; j <= T.size(); j++)
{
a = ta[j];
if (S[i-1] == T[j-1]) ta[j] += b;
b = a;
if (b == 0) break;
}
}
return ta[T.size()];
}
//神奇的通过的程序--逆向填表法
int numDistinct2(string S, string T) {
vector<int> ta(T.size()+1);
ta[0] = 1;
for (int i = 0; i < S.size(); i++)
{
for (int j = T.size()-1; j >= 0; j--)
{
ta[j+1] += (S[i]==T[j])*ta[j];
}
}
return ta[T.size()];
}
//2014-2-17 update
int numDistinct(string S, string T)
{
int *table = new int[T.length()+1];
table[0] = 1;
for (int i = 1; i <= T.length(); i++)
{
table[i] = 0;
}
for (int i = 0; i < S.length(); i++)
{
int j = i<T.length()?i:T.length();
for (; j >= 0; j--)
{
if (T[j] == S[i]) table[j+1] += table[j];//把握全局,逆向填表
}
}
return table[T.length()];
}
分享到:
相关推荐
leetcode刷题之动态规划
资源LeetCode__动态规划实用知识库分享知识分享
javascript javascript_leetcode面试题解动态规划问题之第494题_题解
javascript javascript_leetcode面试题解动态规划问题之第198题打家劫舍_题解
115.Distinct_Subsequences不同的子序列【LeetCode单题讲解系列】
javascript javascript_leetcode面试题解动态规划问题之第22题括号生成_题解
javascript javascript_leetcode面试题解动态规划问题之第221题最大正方形_题解
javascript javascript_leetcode面试题解动态规划问题之第139题单词拆分_题解
javascript javascript_leetcode面试题解动态规划问题之第70题爬楼梯_题解
javascript javascript_leetcode面试题解动态规划问题之第64题最小路径和_题解
javascript javascript_leetcode面试题解动态规划问题之第435题无重叠区间_题解
javascript javascript_leetcode面试题解动态规划问题之第279题完全平方数_题解
javascript javascript_leetcode面试题解动态规划问题之第474题一和零_题解
javascript javascript_leetcode面试题解动态规划问题之第416题分割等和子集_题解
javascript javascript_leetcode面试题解动态规划问题之第718题最长重复子数组_题解
javascript javascript_leetcode面试题解动态规划问题之第931题下降路径最小和_题解
javascript javascript_leetcode面试题解动态规划问题之第300题最长上升子序列_题解
javascript javascript_leetcode面试题解动态规划问题之第152题乘积最大子数组_题解
javascript javascript_leetcode面试题解动态规划问题之第1143题最长公共子序列_题解
javascript javascript_leetcode面试题解动态规划问题之第53题最大子序和_题解