子序列 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 出现的个数.一个字符串的一个子序列是指:通过删除一些(也可以不删除)字符且不干扰剩余字符相对位置所组成的新字符串.(譬如," ...
随机推荐
- [Ubuntu] sogou中文输入法安装
I install sogou 中文输入法 successfully, after following below steps: 1. install sogou pingyin by deb pac ...
- python socket详解
Python 提供了两个基本的 socket 模块. 第一个是 Socket,它提供了标准的 BSD Sockets API. 第二个是 SocketServer, 它提供了服务器中心类,可以简化网络 ...
- Flip the Bits(思维)
You are given a positive integer n. Your task is to build a number m by flipping the minimum number ...
- HTML5+规范:Webview的使用详解
一.知识点 Webview模块管理应用窗口界面,实现多窗口的逻辑控制管理操作.通过plus.webview可获取应用界面管理对象. 1.方法 1.1.all: 获取所有Webview窗口 Array[ ...
- MySQL 事物机制
前言:事物:一组原子性的SQL查询,或多个SQL语句组成了一个独立的单元.要么这一组SQL语句全部执行,要么全部不执行 (一)事物日志介绍:管理事物机制的日志 redo日志:记录SQL执行的语句,这些 ...
- 奇异值分解(SVD)原理详解及推导(转载)
转载请声明出处http://blog.csdn.net/zhongkejingwang/article/details/43053513 在网上看到有很多文章介绍SVD的,讲的也都不错,但是感觉还是有 ...
- 【leetcode】59.Spiral Matrix II
Leetcode59 Spiral Matrix II Given an integer n, generate a square matrix filled with elements from 1 ...
- PHP中类型约束
类型约束 什么叫类型约束? 就是要求某个变量只能使用(接收,存储)某种指定的数据类型: php属于“弱类型语言”,通常不支持类型约束: 相应的,强类型语言,类型约束却是其“基本特征”. php中,只支 ...
- vue render & array of components & vue for & vue-jsx
vue render & array of components & vue for & vue-jsx https://www.cnblogs.com/xgqfrms/p/1 ...
- oracle锁与死锁概念,阻塞产生的原因以及解决方案
锁是一种机制,一直存在:死锁是一种错误,尽量避免. 首先,要理解锁和死锁的概念: 1.锁: 定义:简单的说,锁是数据库为了保证数据的一致性而存在的一种机制,其他数据库一样有,只不过实现机制上可能大 ...