首页 > 代码库 > 最长递增子序列

最长递增子序列

1. 动态规划,使用一个数组保存当前的最大递增子序列长度,时间复杂度为O(N^2)

# include <iostream>
# include <cstdlib>
# include <climits>
using namespace std;

int longestsub(int a[],int n)
{
	int *dis=(int *)malloc((n+1)*sizeof(int));
	dis[0]=1;
	int i,j;
	for(i=0;i<n;i++)
		dis[i]=1;
	for(i=0;i<n;i++)
	{
	for(j=i-1;j>=0;j--)
	{
	if(a[i]>a[j]&&dis[i]<dis[j]+1)
	{
	dis[i]=dis[j]+1;
	}
	}
	}
	int ans=-1;
	for(i=0;i<n;i++)
		ans=max(ans,dis[i]);
	free(dis);
	return ans;
}

int main()
{
	int a[5]={3,6,5,4,7};
	cout<<longestsub2(a,5)<<endl;
    system("pause");
    return 0;
}

2.《编程之美》上提供了另外一种解法,使用数组b[len-1]表示长度为len时最后一个元素值,在这种解法中可以使用二分查找使得程序加速,时间复杂度变为O(N*logN)

# include <iostream>
# include <cstdlib>
# include <climits>
using namespace std;

int binsearch(int a[],int n,int target)  //binarysearch
{
int low=0;
int high=n-1;
int mid;
while(low<=high)
{
mid=(high-low)/2+low;
if(a[mid]==target)
	return mid;
else if(a[mid]<target)
	low=mid+1;
else 
	high=mid-1;
}
return low;
}

int longestsub2(int a[],int n)
{
	int i=0;
	int len=1;
	int *b=(int *)malloc((n+1)*sizeof(int));
	b[0]=a[0];
	for(i=1;i<n;i++)
	{
	if(a[i]>b[len-1])
	{
	b[len]=a[i];
	len++;
	}
	else 
	{
	int tmp=binsearch(a,n,a[i]);
	b[tmp]=a[i];
	}
	}
	free(b);
	return len;
}

int main()
{
	int a[5]={7,6,8,4,1};
	cout<<longestsub2(a,5)<<endl;
    system("pause");
    return 0;
}