最长公共子序列 LCS

算法导论上的LCS算法,动态规划的代表性算法

实现了一下,只是简单地找到一个LCS,并未全部列举出


#include <iostream>
#include <stack>


using namespace std;

enum direct{LEFT = 0, UP, LEFT_UP};

void LCS(char *str1, char *str2){
	
	const int length1 = strlen(str1);
	const int length2 = strlen(str2);

	int **common = new int*[length1 + 1];
	for(int i = 0; i <= length1; ++i)
		common[i] = new int[length2 + 1];

	direct **directions = new direct*[length1 + 1];
	for(int i = 0; i <= length1; ++i)
		directions[i] = new direct[length2 + 1];
	
	for(int i = 0; i <= length1; ++i)
		common[i][0] = 0;
	for(int i = 0; i <= length2; ++i)
		common[0][i] = 0;

	for(int i = 1; i <= length1; ++i)
		for(int j = 1; j <= length2; ++j){
			if(str1[i - 1] == str2[j - 1]){
				common[i][j] = common[i - 1][j - 1] + 1;
				directions[i][j] = LEFT_UP;
			}
			else{
				if(common[i - 1][j] >= common[i][j - 1]){
					common[i][j] = common[i - 1][j];
					directions[i][j] = LEFT;
				}
				else{
					common[i][j] = common[i][j - 1];
					directions[i][j] = UP;
				}			
			}
		}

	cout << "the longest common subsequence's size is: " 
		<< common[length1][length2] << '\n';

	stack<char> st;
	int l1 = length1;
	int l2 = length2;
	while(l1 > 0 && l2 > 0){
		if(directions[l1][l2] == LEFT_UP){
			st.push(str1[l1 - 1]);
			--l1;
			--l2;
		}
		else if(directions[l1][l2] == LEFT)
			--l1;
		else
			--l2;
	}

	cout << "one of the LCS is: ";
	while(!st.empty()){
		cout << st.top();
		st.pop();
	}
	cout << endl;
}


int main(){

	LCS("as222d211f", "as1d2f2");
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值