The Longest increasing subsequence

The task is to find the length of the longest subsequence in a given array of integers such that all elements of the subsequence are sorted in ascending order. For example, the length of the LIS for { 15, 27, 14, 38, 26, 55, 46, 65, 85 } is 6 and the longest increasing subsequence is {15, 27, 38, 55, 65, 85}. 

O(n^2) time cost,O(n) space cost Solution

int LIS(int A[],int n){
	int *L = (int *) malloc(n*sizeof(int));
	int res = 1;
	L[0]=1;  //L[i] is the length of LIS that is end with A[i]
	for(int i=1;i<n;i++){
		int r = 0; //r is length of the longest increasing sub-seq 
                  //whose last element is smaller than A[i]
		for(int j=0;j<i;j++){
			if(A[j]<A[i]) r = max(r,L[j]); 
		}
		L[i] = r+1; 
		res = max(res,L[i]);
	}
	return res;
}

可以在内循环优化,维持一个动态数组 c[], c[i]表示长度为 i 的递增子序列的最小尾部值, 这样就有
c[1]<c[2]<...<c[L] ,注意是严格递增的,最后LIS的长度就是 L

O(n * log n) time cost, O(L) space cost
int LIS(int A[],int n){
	vector<int> c;  //c[i] = min{ 长度为i的上升序列的尾部值 }
	c.push_back(INT_MIN); 
	for(int i=0;i<n;i++){
		int k= lower_bound(c.begin(),c.end(),A[i]) - c.begin();
		if(k==c.size()) c.push_back(A[i]); //找到更长的递增序列
		else c[k]=A[i];   //更新c[k]
	}
	return c.size()-1;
}

Another Awesome Solution

算法复杂度与上一个相同,原来亦同,只不过是借助 C++ set

int LIS(int A[],int n){
	set<int> tab;
	pair<set<int>::iterator,bool> it;
	for(int i=0;i<n;i++){
		it = tab.insert(A[i]);
		if(it.second==true && (++it.first)!=tab.end()) tab.erase(it.first);
	}
	return tab.size();
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值