关于最长公共子序列问题的空间优化

/**
 * 最长公共子序列
 * 优化了内存空间的使用
 * 观察到一件事: 每一个元素的计算,只和其在左上, 左边, 上边的三个元素相关
 * 可以考虑len(x) + 3
 * 3个变量 定义为leftAbove, left, above
 */
#include<iostream>
#include<string>
#include<memory.h>
using namespace std;


int LCS(string x, string y);
 
int main() {
	string x, y;
	cin>>x>>y;
	LCS(x, y);
}

int LCS(string x, string y){
	int lenx = x.length();
	int leny = y.length();
	
	int leftabove, left, above; //左上角 左 上

	int *compute = new int[leny + 1]; //compute[0] 即原来的calc[i][0] for i in [0, lenx];
	memset(compute, 0, (leny + 1) * sizeof(int));
	for(int i = 1; i <= lenx; i++) {
		leftabove = left = compute[0];
		above = compute[1];
		for(int t = 0; t <= leny; t++) cout<<compute[t]<<" ";
		cout<<endl;
		for(int j = 1; j <= leny; j++) { 
			//计算,并且更新这三个变量
			if(x[i - 1] == y[j - 1]) compute[j] = leftabove + 1;
			else if(left > above) 	compute[j] = left;
			else compute[j] = above;

			//更新此三个变量,很有技巧的哦
			leftabove = above;
			above = compute[j + 1];
			left = compute[j];
		}
	}
	cout<<compute[leny]<<endl; 
	delete[] compute;
}

受一篇文章启发

http://blog.csdn.net/oyzdz1988/article/details/4456443

发现可以把空间减少到min{lenX, lenY} +O(1) 上述就是代码



从这个题目得到一点认识:只做足够,优化到极致.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值