对于什么是子序列和公共子序列,这里不再进行赘述,直接切入主题。
首先遇到这类问题,可能会首先想到穷举进行毕竟,但是穷举出一个长度为n的串的子序列,有2的n次方种情况,那么对于时间复杂度将会是指数级的,所以需要用dp的思想进行求解。
我们先设两个字符串A,B
Ax为前x个连续字符组成的子序列,同理可得by的含义。
那么比较Ax和By的最后一个字符ax和by
情况一:ax == by
那么ax和by一定是Ax和By的最长公共子序列的最后一个字符,所以我们只需要求LCS(Ax - 1,By - 1)的最长公共子序列 + 1即可得出LCS(Ax,By)。
情况二:ax != by
那么Ax和By的最长公共子序列的最后一位一定满足 t != ax || t != by,那么我们就只需要求出MAX( LCS( Ax - 1,By ),LCS( Ax,By - 1 ) )即是Ax和By的最大公共子序列。
由情况一二可得,我们将改任务不断分解成子任务,就是dp的特征之一,我们由此可得递推式
由此可得代码(自底向上的dp)
void Lcs(string s1,string s2){
for(int i = 1; i <= s1.size(); i++){
for(int j = 1; j <= s2.size(); j++){
if(s1[i - 1] == s2[j - 1]){
dpmaxlenth[i][j] = dpmaxlenth[i - 1][j - 1] + 1;
}
else if(dpmaxlenth[i - 1][j] >= dpmaxlenth[i][j - 1]){
dpmaxlenth[i][j] = dpmaxlenth[i - 1][j];
}
else{
dpmaxlenth[i][j] = dpmaxlenth[i][j - 1];
}
}
}
}
这里的0既是空序列的最大公共子序列数为0。
若要使对程序运行的过程进行直观和详细的解释可以参考这位博主的文章 传送门
因为后面在进行求具体某一个最长公共子序列的时候,如果不清楚程序过程的话,对我来说,会有些困难。
这里先给出一个模板题Common Subsequence
单纯的求最大公共子序列的长度
代码如下
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
int dpmaxlenth[1005][1005];
void Lcs(string s1,string s2){
for(int i = 1; i <= s1.size(); i++){
for(int j = 1; j <= s2.size(); j++){
if(s1[i - 1] == s2[j - 1]){
dpmaxlenth[i][j] = dpmaxlenth[i - 1][j - 1] + 1;
}
else if(dpmaxlenth[i - 1][j] >= dpmaxlenth[i][j - 1]){
dpmaxlenth[i][j] = dpmaxlenth[i - 1][j];
}
else{
dpmaxlenth[i][j] = dpmaxlenth[i][j - 1];
}
}
}
}
int main(){
string s1,s2;
while(cin>>s1>>s2){
memset(dpmaxlenth,0,sizeof(dpmaxlenth));
Lcs(s1,s2);
cout<<dpmaxlenth[s1.size()][s2.size()]<<endl;
}
return 0;
}
对于求具体的最长公共子序列,首先我们要知道,有时候解不唯一,所以我们求任意一个即可
如图,即从终点进行回溯。
例题1006 最长公共子序列Lcs
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
int dpmaxlenth[1005][1005];
void Lcs(string s1,string s2){
for(int i = 1; i <= s1.size(); i++){
for(int j = 1; j <= s2.size(); j++){
if(s1[i - 1] == s2[j - 1]){
dpmaxlenth[i][j] = dpmaxlenth[i - 1][j - 1] + 1;
}
else if(dpmaxlenth[i - 1][j] >= dpmaxlenth[i][j - 1]){
dpmaxlenth[i][j] = dpmaxlenth[i - 1][j];
}
else{
dpmaxlenth[i][j] = dpmaxlenth[i][j - 1];
}
}
}
}
void llcs(string s1,string s2){
char s3[1005];
int i = s1.size(),j = s2.size(),k = 0;
while(i != 0&&j != 0){
if(s1[i - 1] == s2[j - 1]){
i--,j--,k++;
s3[k] = s1[i];
}
else if(dpmaxlenth[i - 1][j] < dpmaxlenth[i][j - 1]){
j--;
}
else{
i--;
}
}
for(int z = k; z >= 1; z--){
cout<<s3[z];
}
cout<<endl;
}
int main(){
string s1,s2;
while(cin>>s1>>s2){
memset(dpmaxlenth,0,sizeof(dpmaxlenth));
Lcs(s1,s2);
llcs(s1,s2);
}
return 0;
}