300. Longest Increasing Subsequence

来源:互联网 发布:数据库中的索引是什么 编辑:程序博客网 时间:2024/05/21 11:36
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?


第二遍 还是没做出来 。。。  
倒是很快看明白了 知道应该用dp 就想一下 dp存什么 后面的能继续使用
难点还在于 递推表达式不好想 应该是 

dp[i]=max(dp[j])+1,0j<i

LISlength=max(dp[i]),0i<n

10 9 2 5 3 4 7

怎样是2,3,4 而不是2,5 也就是怎样让3能接上2?
遍历3之前所有可以接上的

public int lengthOfLIS(int[] nums) {        if (nums.length == 0) {            return 0;        }        int[] dp = new int[nums.length];        dp[0] = 1;        int maxans = 1;        for (int i = 1; i < dp.length; i++) {            int maxval = 0;            for (int j = 0; j < i; j++) {                                         if (nums[i] > nums[j]) {//找出所有将nums[i]加入仍然是递增序列的序列                    maxval = Math.max(maxval, dp[j]);//选择长度最大的那个 拼接上nums[i] 这样 就还是最长的子序列                }            }            dp[i] = maxval + 1;            maxans = Math.max(maxans, dp[i]);        }        return maxans;    }

//也就是说 从dp[i]是指可以将nums[i]加入之后仍然是递增子序列中 长度最大的那个 dp[0]到dp[n]分别代表把dp[i]包含进来 最长的递增子序列 然后取最长的长度就可以了
阅读全文
0 0