(java)求最长递增子序列(可以不连续的情况)

来源:互联网 发布:sai mac版本 编辑:程序博客网 时间:2024/05/31 20:51

题目大意:

Given an unsorted array of integers, find the length of longest increasing subsequence.


For example,
Given [10, 9, 2, 5, 3, 7, 101, 18],
The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length.

Your algorithm should run in O(n2) complexity.

Follow up: Could you improve it to O(n log n) time complexity?

其中我的O(N2)的代码如下:就是动态规划,其中把最长路径保存了下来。。。

统计前面的数字的长度,然后后面的长度是(如果大于前面的数且长度+1大于原来的长度则更新现在的长度),代码很清晰,如下:

package aaa;public class Main7 {public static void main(String[] args) {// TODO 自动生成的方法存根        int[] n=new int[]{1,5,8,3,6,7,2,9};        find(n);}public static void find(int[] a){int[] L=new int[a.length];for(int i=0;i<a.length;i++){L[i]=1;for(int j=0;j<i;j++){if(a[j]<a[i] && L[j]+1>L[i]){L[i]=L[j]+1;}}}int max=0;int index=0;for(int i=0;i<L.length;i++){if(L[i]>max){max=L[i];index=i;}}int length=max;System.out.println(max+":"+index);int[] r=new int[max];for(int i=index;i>=0;i--){if(L[i]==max){max=max-1;r[max]=a[i];}}for(int i=0;i<length;i++){System.out.println(r[i]+" ");}}}


0 0