300. Longest Increasing Subsequence java solutions

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:
Special thanks to @pbrother for adding this problem and creating all test cases.

 1 public class Solution {
 2     public int lengthOfLIS(int[] nums) {
 3         if(nums == null || nums.length == 0) return 0;
 4         int[] dp = new int[nums.length];
 5         int max = 0;
 6         Arrays.fill(dp,1);
 7         for(int i = 0; i<nums.length; i++){
 8             for(int j = 0; j <= i;j++){
 9                 if(nums[i] > nums[j] && dp[j] + 1 > dp[i])
10                     dp[i] = dp[j] + 1;
11             }
12             max = Math.max(max,dp[i]);
13         }
14         return max;
15     }
16 }

依次遍历整个序列,每一次求出从第一个数到当前这个数的最长上升子序列,直至遍历到最后一个数字为止,然后再取dp数组里最大的那个即为整个序列的最长上升子序列。

我们用dp[i]来存放序列1-i的最长上升子序列的长度,那么dp[i]=max(dp[j])+1,(j∈[1, i-1]); 显然dp[1]=1,我们从i=2开始遍历后面的元素即可。

该题基本解法O(n*n), 优化解法O(nlogn) 二刷时候再解。

posted @ 2016-07-03 13:07  Miller1991  阅读(261)  评论(0编辑  收藏  举报