最长公共子序列LCS递归解法

#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);
	}
}
void init()
{
	int i,j;
	cin>>str1>>str2;
	if(str1==str2)
	{
		cout<<str1<<endl;
		flag=false;
		return;
	}
	row=str1.length();
	col=str2.length();
	
	record=new char[row>col?row:col]();
	lcs=new char[row>col?row:col]();
	map=new int*[row];
	index=maxLen=0;
	
	for(i=0;i<row;i++)
		map[i]=new int[col]();

	for(i=0;i<row;i++)
		for(j=0;j<col;j++)
			if(str1[i]==str2[j])
				map[i][j]=1;
}
void delMem()
{
	for(int i=0;i<row;i++)
		delete[] map[i];
	delete[] map;
}
int main()
{
	init();
	if(flag)
	{
		dfs(0,0);
	
		cout<<lcs<<endl;

		cout<<maxLen<<endl;

		cout<<strlen(lcs)<<endl;

		delMem();
	}
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值