#include<iostream>
#include<string.h>
using namespace std;
int row,col,**map,index,maxLen;
char *record,*lcs;
bool flag=true;
string str1,str2;
/*
eg: str1="abcb",str2="acb"
a b c b
a 1 0 0 0
c 0 0 1 0
b 0 1 0 1
map: 如上,以str1长度为row,str2长度为col,当str1[i]==str2[j],map[i][j]=1;
index:代表record中某时刻的元素个数
maxLen: 存放dfs过程中,出现的临时最长子序列长度
record:存放dfs过程中符合条件的CS
lcs:存放最终的LCS
flag:控制结果,当str1==str2直接输出,不比dfs
思路:先得到map数组,之后从左上至右下开始dfs,每遇到一个1,则跳向下一行的下一列,
到边界返回并判断得到的CS是否比原来的CS更长. (临时做出来,没有优化算法
,感觉效率不高,先用着...)
*/
void dfs(int r,int c)//r代表临时的行,c代表临时的列
{
for(int i=r;i<row;i++)
for(int j=c;j<col;j++)
if(map[i][j]==1)
{
record[index]=str1[i];
index++;
dfs(i+1,j+1);
index--;
record[index]=0;
}
if(maxLen<index)
{
maxLen=index;
strcpy(lcs,record);
最长公共子序列LCS递归解法
最新推荐文章于 2022-07-03 15:51:15 发布