引言

子序列和子字符串或者连续子集的不同之处在于,子序列不需要是原序列上连续的值。

对于子序列的题目,大多数需要用到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(求子序列个数)的更多相关文章

  1. [Leetcode] distinct subsequences 不同子序列

    Given a string S and a string T, count the number of distinct subsequences of T in S. A subsequence ...

  2. 【线型DP模板】最上上升子序列(LIS),最长公共子序列(LCS),最长公共上升子序列(LCIS)

    BEGIN LIS: 一个数的序列bi,当b1 < b2 < … < bS的时候,我们称这个序列是上升的.对于给定的一个序列(a1, a2, …, aN),我们可以得到一些上升的子序 ...

  3. 经典算法-最长公共子序列(LCS)与最长公共子串(DP)

    public static int lcs(String str1, String str2) { int len1 = str1.length(); int len2 = str2.length() ...

  4. 最长公共前缀 leetcode 14

    方法一(纵向扫描) 解题思路 先计算出数组中最小的字符串长度,这样就避免了越界的情况,思路更加明确,但同时时间复杂度就相应的上升了. 先计算所有字符串在同一列上的字符是否相同,然后依次向后延伸. 代码 ...

  5. 14. 最长公共前缀----LeetCode

    编写一个函数来查找字符串数组中的最长公共前缀. 如果不存在公共前缀,返回空字符串 "". 示例 1: 输入: ["flower","flow" ...

  6. [LeetCode] Distinct Subsequences 不同的子序列

    Given a string S and a string T, count the number of distinct subsequences of T in S. A subsequence ...

  7. DP————LIS(最长上升子序列)和LCS(最长公共子序列)问题

    LIS问题 https://www.acwing.com/problem/content/898/ 思路:首先数组a中存输入的数(原本的数),开辟一个数组f用来存结果,最终数组f的长度就是最终的答案: ...

  8. [LeetCode] Increasing Subsequences 递增子序列

    Given an integer array, your task is to find all the different possible increasing subsequences of t ...

  9. 115 Distinct Subsequences 不同子序列

    给定一个字符串 S 和一个字符串 T,求 S 的不同的子序列中 T 出现的个数.一个字符串的一个子序列是指:通过删除一些(也可以不删除)字符且不干扰剩余字符相对位置所组成的新字符串.(譬如," ...

随机推荐

  1. PHPDoc 学习记录

    https://zh.wikipedia.org/wiki/PHPDoc PHPDoc 是一个 PHP 版的 Javadoc.它是一种注释 PHP 代码的正式标准.它支持通过类似 phpDocumen ...

  2. php中注释有关内容

    //单行注释 /*多行注释*/ /** 文档注释 (注意 文档注释与前面的那个多行注释不同)文档注释可以和特定的程序元素相关联 例如 类 函数 常量 变量方法 问了将文档注释与元素相关联 只需要在元素 ...

  3. curl和file_get_contents 区别以及各自的优劣

    PHP中fopen,file_get_contents,curl函数的区别: 1.fopen /file_get_contents 每次请求都会重新做DNS查询,并不对 DNS信息进行缓存.但是CUR ...

  4. Scrum立会报告+燃尽图(十一月二十三日总第三十一次):界面修改及新页面添加

    此作业要求参见:https://edu.cnblogs.com/campus/nenu/2018fall/homework/2410 项目地址:https://git.coding.net/zhang ...

  5. scrum立会报告+燃尽图(第二周第七次)

    此作业要求参见:https://edu.cnblogs.com/campus/nenu/2018fall/homework/2252 一.小组介绍 组名:杨老师粉丝群 组长:乔静玉 组员:吴奕瑶.公冶 ...

  6. Alpha冲刺——第五天

    Alpha第五天 听说 031502543 周龙荣(队长) 031502615 李家鹏 031502632 伍晨薇 031502637 张柽 031502639 郑秦 1.前言 任务分配是VV.ZQ. ...

  7. Firefox必备的24款web开发插件

    from: 软件过滤: 排序:收录时间 | 浏览数 网页开发FireFox插件 Firebug Firebug是Firefox下的一款开发类插件,现属于Firefox的 五星级强力推荐插件之一.它集H ...

  8. C#中委托的理解

    请注意,这只是个人关于C#中委托的一点点理解,参考了一些博客,如有不周之处,请指出,谢谢! 委托是一种函数指针,委托是方法的抽象,方法是委托的实例.委托是C#语言的一道坎,明白了委托才能算是C#真正入 ...

  9. Docker 技术 介绍

    https://github.com/docker/docker 实现用户空间隔离的技术:名称空间(NameSpace),CGroup(控制组) 什么是NameSpace::简单的理解就是,每一个虚拟 ...

  10. HDU 2132 An easy problem

    http://acm.hdu.edu.cn/showproblem.php?pid=2132 Problem Description We once did a lot of recursional ...