码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-03-17 14:13:17      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

#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;
}

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

标签:

原文地址:http://blog.csdn.net/lc0817/article/details/44340743

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!