子序列 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 出现的个数.一个字符串的一个子序列是指:通过删除一些(也可以不删除)字符且不干扰剩余字符相对位置所组成的新字符串.(譬如," ...
随机推荐
- ES6的新特性(9)——对象的扩展
对象的扩展 属性的简洁表示法 ES6 允许直接写入变量和函数,作为对象的属性和方法.这样的书写更加简洁. const foo = 'bar'; const baz = {foo}; baz // {f ...
- 你应该知道的PHP库
Libchart – 这也是一个简单的统计图库. JpGraph – 一个面向对象的图片创建类. Open Flash Chart – 这是一个基于Flash的统计图. RSS 解析 解释RSS并是一 ...
- Alpha 冲刺(4/10)
队名 火箭少男100 组长博客 林燊大哥 作业博客 Alpha 冲鸭鸭鸭鸭! 成员冲刺阶段情况 林燊(组长) 过去两天完成了哪些任务 协调各成员之间的工作 协助前后端接口的开发 测试项目运行的服务器环 ...
- 测试——约跑APP
项目名:约跑APP 用户需求规格说明书URL:http://www.cnblogs.com/liquan/p/6071804.html 组长博客URL:http://www.cnblogs.com/l ...
- 【开发工具IDE】JAVA-eclipse使用汇集
-------------------------------------------------------------------------------------------------- 1 ...
- 51nod 1526 分配笔名(字典树+贪心)
题意: 班里有n个同学.老师为他们选了n个笔名.现在要把这些笔名分配给每一个同学,每一个同学分配到一个笔名,每一个笔名必须分配给某个同学.现在定义笔名和真名之间的相关度是他们之间的最长公共前缀.设笔名 ...
- 表单验证2-JS正则
1. JS正则: 以/开头,以/结尾. test作用:到里面去找,只要里面有,就返回true:否则就返回false. 例如:rep=/\d+/; 检验里面是否有数字. 2.rep=/^ $/; ...
- hihoCoder #1639 图书馆
题目大意 给定 $n$($1\le n\le 1000$)个正整数 $a_1, a_2, \dots, a_n$($a_i \le 10^{12}$),令 $s$ 为这 $n$ 个数之和.求 $$ \ ...
- Opencv2.4.9+win7+VS2012一次性配置的方法--通过建立属性表永久配置
Opencv的配置对于初学者很麻烦,网上的教程也非常多,针对不同的操作系统.opencv版本.Visual studio版本都有相应的教程,但即便是按照教程一步一步来,仍然难免出错,很多教程还是一次性 ...
- 【入门OJ】2003: [Noip模拟题]寻找羔羊
这里可以复制样例: 样例输入: agnusbgnus 样例输出: 6 这里是链接:[入门OJ]2003: [Noip模拟题]寻找羔羊 这里是题解: 题目是求子串个数,且要求简单去重. 对于一个例子(a ...