Longest Increasing Subsequence

来源:互联网 发布:歌曲串烧制作软件 编辑:程序博客网 时间:2024/05/01 22:22

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[i] 表示的物理意义是,以i为最后一个char,到此为止所能够表示的最长的递增子序列,那么递推公式就是 dp[i] = Math.max( dp[i], 1+dp[j])  0< j < i ,这里是所有小于i的j,都要进行一次比较,当array[j]< array[i]的时候,进行更新。最后是要找出这个dp序列里面的最大值,返回。

public class Solution {    public int lengthOfLIS(int[] nums) {        if(nums == null || nums.length == 0) return 0;        int[] dp = new int[nums.length];        for(int i=0; i<dp.length; i++){            dp[i] = 1;        }                int max = 0;        for(int i=0; i<dp.length; i++){            for(int j=0; j<i; j++){                if(nums[j]<nums[i]) {                    dp[i] = Math.max( 1+dp[j], dp[i] );                }            }            max = Math.max(max, dp[i]);        }        return max;    }}
nlogn的解法: https://segmentfault.com/a/1190000003819886

http://www.cnblogs.com/grandyang/p/4938187.html



0 0
原创粉丝点击