子序列 sub sequence问题,例:最长公共子序列,[LeetCode] Distinct Subsequences(求子序列个数)
引言
子序列和子字符串或者连续子集的不同之处在于,子序列不需要是原序列上连续的值。
对于子序列的题目,大多数需要用到DP的思想,因此,状态转移是关键。
这里摘录两个常见子序列问题及其解法。
例题1, 最长公共子序列
我们知道最长公共子串的求法,先温习一下,它的求法也是使用DP思想,对于 字符串s1 和字符串s2,令 m[i][j] 表示 s1上以s1[i]结尾的子串和s2上s2[j]结尾的子串的最长公共子串长度,因为公共子串必须是连续的,因此状态转移方程:m[i, j] = (s1[i] == s2[j] ? m[i-1, j-1] + 1 : 0)。因为m[i, j]的计算只需要用到 m[i-1, j-1],再之前的就用不着了,因此我们不必用一个二维数组来保存整个m[s1.length()][s2.length()],只需要保存并不断更新m[i-1, j-1]就可以了。
代码:
char *LCString(const char* s1, const char* s2){
if(NULL == s1 || NULL == s2)
return NULL;
int size1 = , size2 = ;
const char* head1 = s1; const char* head2 = s2;
while(*(head1++) != '\0') size1++;
while(*(head2++) != '\0') size2++;
printf("%d, %d\n", size1, size2);
int maxlen = , maxend = , i = , j = , tmpPre = ;
int m2[size2];
for(i = ; i < size2; m2[i] = , ++i);
for(i = ; i < size1; ++i){
for(j = ; j < size2; ++j){
int len = ((s1[i] == s2[j] ? : ) + (j > ? tmpPre : ));
if(len > maxlen) { maxlen = len; maxend = i;}
tmpPre = m2[j];
m2[j] = len;
}
}
if(maxlen > ){//提出最长子字符串
char* lcs = new char[maxlen + ];
for(i = ; i < maxlen; lcs[maxlen - i - ] = s1[maxend - i], i++);
lcs[maxlen] = '\0';
return lcs;
}
return NULL;
}
那么,对于最长公共子序列,如何去求呢?
首先,如果用m[][]来存长度,最后提出最长子序列要麻烦一些,因为子序列是不连续的。不过虽然麻烦,依旧可行。
接着,依然假设m[i, j]表示 s1[i]结尾的子串 和s2[j]结尾的子串的 最长公共子序列的长度。
那么:
若s1[i] == s2[j],m[i,j] = m[i-1][j-1] + 1;
若s1[i] != s2[j],m[i,j] = Max(m[i-1][j], m[i][j-1])。
这里因为求 m[i,j] 时,m[i-1][j], m[i][j-1], m[i-1][j-1]都有可能用到,因此咱还是老实一点用 二维数组吧。。
template <typename T> T* Lcseq(T* list1, int size1, T* list2, int size2){
if(NULL == list1 || NULL == list2)
return NULL;
int** m = new int*[size1];
int i = , j = ;
int max = , maxi = , maxj = ;
for(; i < size1; i++){
m[i] = new int[size2];
for(j = ; j < size2; j++){
if(i == && j == ) m[][] = (list1[] == list2[] ? : );
else if(i == ) m[i][j] = (list1[i] == list2[j] ? : m[i][j-]);
else if(j == ) m[i][j] = (list1[i] == list2[j] ? : m[i-][j]);
else m[i][j] = (list1[i] == list2[j] ? m[i-][j-] + : (m[i][j-] > m[i-][j] ? m[i][j-] : m[i-][j]));
if(m[i][j] > max){
max = m[i][j];
maxi = i;
maxj = j;
}
}
}
//printf("%d, %d, %d\n", max, maxi, maxj);
//提取最大公共子序列
int p1 = maxi, p2 = maxj, p = max;
T* sub = new T[max];
while(p1 >= && p2 >= ){
if(list1[p1] == list2[p2]){
sub[--p] = list1[p1];
//printf("p: %d, p1: %d, p2: %d\n", p, p1, p2);
p1--;
p2--;
}
else{
if(p1 == ) p2--;
else if(p2 == ) p1--;
else{
if(m[p1-][p2] < m[p1][p2-]) p2--;
else p1--;
}
}
}
return sub;
}
例题2,求子序列的个数,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.
class Solution {
public:
int numDistinct(string S, string T) {
}
};
如果不用DP,用带记忆的递归也能做,就是时间比较长,而且递归需要额外的栈空间。
class Solution {
public:
int numDistinct(string S, string T) {
if(T.length() == ) return ;
if(S.length() == ) return ;
rec = new int*[S.length()];
for(int i = ;i < S.length(); ++i){
rec[i] = new int[T.length()];
for(int j = ;j < T.length(); ++j)
rec[i][j] = -;
}
return numDistinctCore(S, T, ,);
}
int numDistinctCore(string S, string T, int p1, int p2) {
if(p2 == T.length()) return ;
if((T.length()-p2) > (S.length()-p1)) return ;
if(rec[p1][p2] >= ) return rec[p1][p2];
int sum = ;
for(int i = p1;i < S.length(); ++i){
if(S[i] == T[p2])
sum += numDistinctCore(S, T, i+, p2+);
}
rec[p1][p2] = sum;
return sum;
}
private:
int **rec;
};
AC时间 388ms。
引入DP思想的话,我们依旧用rec[i][j] 表示 "S[i]结尾子串" 中包含 "T[j]结尾子串" 的 sequence 个数。
因为S[i]子串 包含了S[i-1]子串,所以rec[i][j] 至少等于rec[i-1][j];同时,如果S[i] == T[j],那么还可以让 S[i]和T[j] 匹配,这种情况下,sequence个数就是rec[i-1][j-1]。
rec[i][j] = rec[i-1][j] + (S[i] == T[j] ? rec[i-1][j-1] : 0)。
代码:
class Solution {
public:
int numDistinct(string S, string T) {
int slen = S.length(), tlen = T.length();
if(slen < tlen) return ;
int **rec = new int*[slen+];
int i, j;
for(i = ; i <= slen; ++i){
rec[i] = new int[tlen+];
for(j = ; j <= tlen; ++j){
rec[i][j] = ;
}
}
for(i = ; i <= slen; rec[i++][] = );
for(i = ; i <= slen; ++i){
for(j = ; j <= tlen; ++j){
rec[i][j] = (rec[i-][j] + (S[i-] == T[j-] ? rec[i-][j-] : ));
}
}
return rec[slen][tlen];
}
};
AC时间 52ms。大幅提高。
上面的解法用到了二维数组。后来搜到了小磊哥关于这道题的解。让 j 从T末尾遍历,这样rec[i][j] 要么依旧等于 rec[i-1][j],也就是不变,要么加上 rec[i-1][j-1],因为j是从末尾遍历到前面,因此 rec[i-1][j-1] 不会被覆盖。这样做,省去了二维数组,直接一维数组搞定。用match[] 表示 T[j]结尾的子串 的sequence个数。
代码:
class Solution {
public:
int numDistinct(string S, string T) {
if(S.size() < T.size()) return ;
int match[T.size()+];
int i, j;
for(match[] = , i = ; i < T.size(); match[++i] = );
for(i = ; i <= S.size(); ++i)
for(j = T.size(); j >= ; --j)
if(S[i-] == T[j-])
match[j] += match[j-];
return match[T.size()];
}
};
这里也用到了上一篇文章中利用从后往前遍历避免值被覆盖的思想。
16ms AC,只能说,碉堡了。。
子序列 sub sequence问题,例:最长公共子序列,[LeetCode] Distinct Subsequences(求子序列个数)的更多相关文章
- [Leetcode] distinct subsequences 不同子序列
Given a string S and a string T, count the number of distinct subsequences of T in S. A subsequence ...
- 【线型DP模板】最上上升子序列(LIS),最长公共子序列(LCS),最长公共上升子序列(LCIS)
BEGIN LIS: 一个数的序列bi,当b1 < b2 < … < bS的时候,我们称这个序列是上升的.对于给定的一个序列(a1, a2, …, aN),我们可以得到一些上升的子序 ...
- 经典算法-最长公共子序列(LCS)与最长公共子串(DP)
public static int lcs(String str1, String str2) { int len1 = str1.length(); int len2 = str2.length() ...
- 最长公共前缀 leetcode 14
方法一(纵向扫描) 解题思路 先计算出数组中最小的字符串长度,这样就避免了越界的情况,思路更加明确,但同时时间复杂度就相应的上升了. 先计算所有字符串在同一列上的字符是否相同,然后依次向后延伸. 代码 ...
- 14. 最长公共前缀----LeetCode
编写一个函数来查找字符串数组中的最长公共前缀. 如果不存在公共前缀,返回空字符串 "". 示例 1: 输入: ["flower","flow" ...
- [LeetCode] Distinct Subsequences 不同的子序列
Given a string S and a string T, count the number of distinct subsequences of T in S. A subsequence ...
- DP————LIS(最长上升子序列)和LCS(最长公共子序列)问题
LIS问题 https://www.acwing.com/problem/content/898/ 思路:首先数组a中存输入的数(原本的数),开辟一个数组f用来存结果,最终数组f的长度就是最终的答案: ...
- [LeetCode] Increasing Subsequences 递增子序列
Given an integer array, your task is to find all the different possible increasing subsequences of t ...
- 115 Distinct Subsequences 不同子序列
给定一个字符串 S 和一个字符串 T,求 S 的不同的子序列中 T 出现的个数.一个字符串的一个子序列是指:通过删除一些(也可以不删除)字符且不干扰剩余字符相对位置所组成的新字符串.(譬如," ...
随机推荐
- spark RDD、DataFrame、DataSet之间的相互转化
这三个数据集看似经常用,但是真正归纳总结的时候,很容易说不出来 三个之间的关系与区别参考我的另一篇blog http://www.cnblogs.com/xjh713/p/7309507.html ...
- “Hello World!”团队召开的第六次会议
团队“Hello World!”团队召开的第六次会议. 博客内容: 一.会议时间 二.会议地点 三.会议成员 四.会议内容 五.Todo List 六.会议照片 七.燃尽图 一.会议时间 2017年1 ...
- Alpha版发布 - 感谢有你们
在本次alpha开发的过程中,很感谢组长王航对我信任,让我统筹大家的工作任务和进度,使我对项目管理有了深刻的理解. 我也要感谢邹双黛,因为我以前很少做文字类的工作,写东西非常生硬,邹双黛即使在有做家教 ...
- 咱们的team1序章
之前都参加了好多组织,这是第一次参加变成组织.首先要介绍团队名称了,为什么叫“咱们的team”呢,因为,我们需要每个人都认真的参与进来,只有每个人都十分投入地参与进来,这个team才能称之为一个tea ...
- PyCharm如何设置源代码字体的大小
改源代码大小 1.File→Settings→Editor→Colors&Fonts→Font 2.首先得需要Save as一个Scheme,接下来才可以修改字体,名字可以任意取 改运行字体的 ...
- jquery新版本旧版本之间的坑
JQuery自1.6.1版本开始增加一些属性,使用时尽量使用这些新的属性,例如:selected.checked.在高版本中赋值时最好用prop,如果用attr就会出现赋值不成功的问题, 一般自定义属 ...
- 团队项目选题报告(I know)
一.团队成员及分工 团队名称:I know 团队成员: 陈家权:选题报告word撰写 赖晓连:ppt制作,原型设计 雷晶:ppt制作,原型设计 林巧娜:原型设计,博客随笔撰写 庄加鑫:选题报告word ...
- mysql不能启动报error2013错误的解决办法
Mysql mysql lost connection to server during query 问题解决方法 2013-10-16 11:10:53 缘由: 在查询Mysql中的数据库,或者修改 ...
- 小程序获取 openid 和 session_key
<?php //获取openid function getopenid(){//获取用户ID //code为前端通过 wx.login() 方式获取 $code = $_GET["co ...
- IDEA换行CRLF, LF, CR的解释和默认设置
在window下开发有一个大坑,就是换行默认是CRLF,也就是回车换行,但是Linux下只有换行LF,这样代码提交后,会出现编译问题,所以最好的办法是在IDEA下设置默认为LF. 首先我们先介绍CRL ...