Longest Increasing Subsequence

来源:互联网 发布:sql语句update where 编辑:程序博客网 时间:2024/05/16 06:41

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? 

Credits:

自己做出来的一道动规题,细想一下感觉还是挺清晰的。并没有想象中那么难。这段时间开始要刷动规的题了,要加快进度了。

代码:

public int lengthOfLIS(int[] nums) {        if(nums == null || nums.length == 0) return 0;        int [] dp = new int[nums.length];        for(int i=0;i<nums.length;i++)            dp[i] = 1;                    for(int i=1;i<nums.length;i++){            for(int j=0;j<i;j++){                if(nums[j]<nums[i]){                    dp[i] = Math.max(dp[i], dp[j]+1);                }            }        }        int max = -1;        for(int i=0;i<dp.length;i++){            max = Math.max(max, dp[i]);        }        return max;    }


0 0
原创粉丝点击