码迷,mamicode.com
首页 > 其他好文 > 详细

动态规划系列【2】最长递增子序列LIS

时间:2017-03-03 21:22:23      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:动态规划   lis   最长递增子序列   

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.

Subscribe to see which companies asked this question.

题意:无需多说。主要是这玩意有基础版O(n^2)和增强版O(nlogn)

public class Solution {
    public int lengthOfLIS(int[] nums) {
        int length=nums.length;
        if(length==0)return 0;
        int max=1;
        int[] d=new int[length];
        for(int i=1;i<length;i++){
            d[i]=1;
            for(int j=0;j<i;j++){
                if(nums[j]<nums[i])
                  d[i]=Math.min(d[i],d[j]=1);
            }
            max=Math.max(d[i],max);
        }
        return max;
      }
}

PS:思路参加http://www.hawstein.com/posts/dp-novice-to-advanced.html

public class AscentSequence {
    public int findLongest(int[] A, int n) {
        // write code here
        int[] dp=new int[n];
        int[] ends=new int[n];
        ends[0]=A[0];
        dp[0]=1;
        int max=1;
        int r=0,right=0,l=0,m=0;
        for(int i=1;i<n;i++){
            l=0;
            r=right;
            while(l<=r){
                m=(l+r)/2;
                if(A[i]>ends[m]){
                    l=m+1;
                }else{
                    r=m-1;
                }
            }
            //没明白
            right=Math.max(l,right);
            ends[l]=A[i];
            dp[i]=l+1;
            max=Math.max(dp[i],max);
        }
        return max;
    }
}

用二分查找、辅助数组。

动态规划系列【2】最长递增子序列LIS

标签:动态规划   lis   最长递增子序列   

原文地址:http://fulin0532.blog.51cto.com/6233825/1903095

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!