zoukankan      html  css  js  c++  java
  • 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) 二刷时候再解。

  • 相关阅读:
    poj 3087 直接模拟
    POJ-3126 BFS,埃式筛选及黑科技
    POJ3278-Catch That Cow
    js变量提升
    饿了么
    2分钟就能学会的【Google/百度搜索大法】了解一下?
    span标签间距
    Vue移动端项目如何使用手机预览调试
    Port 3000 is already in use
    koa2第一天 async详解
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5637881.html
Copyright © 2011-2022 走看看