题目要求:
求一个数组的最长递减子序列;
比如{9,4,3,2,5,4,3,2}的最长递减子序列为{9,5,4,3,2}。
代码实现:
代码1:动态规划,时间复杂度O(N^2).
#include <iostream> using namespace std; const int N = 8; int Lis(int a[],int n); int main(void) { int a[] = {1,-1,2,1,4,-5,6,-7}; cout << Lis(a,N) << endl; return 0; } int Lis(int a[],int n) { int *B = new int[n]; int i,j,max; for(i = 0;i<n;i++) { B[i] = 1; for(j = 0;j<i;j++) { if(a[i]<a[j] && B[j]+1>B[i]) B[i] = B[j]+1; } } max = B[0]; for(i = 1;i<n;i++) { if(max<B[i]) max = B[i]; } return max; }
代码2:使用二分搜索提速,时间复杂度O(N*logN).
#include <iostream> using namespace std; const int N = 8; int Lis(int a[],int n); int main(void) { int a[] = {1,-1,2,1,4,-5,6,-7}; cout << Lis(a,N) << endl; return 0; } int Lis(int a[],int n) { int *B = new int[n]; int i,left,right,mid,len = 1; B[0] = INT_MAX; B[1] = a[0]; for(i = 1;i<n;i++) { left = 0; right = len; while(left<=right) { mid = (left+right)/2; if(B[mid]>a[i]) left = mid+1; else right = mid-1; } B[left] = a[i]; if(left>len) len++; } return len; }