ITeye博客

Longest Increasing Subsequence

KickCode · 2016-02-28 04:22 · Leetcode · 编程语言 · Markdown

Given an unsorted array of integers, find the length of longest increasing subsequence.

For example, Given , The longest increasing subsequence is , 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(n^2) complexity.

用动态规划解决,时间复杂度为O(n^2)。创建一个动态数组dp,维护一个变量max来记录最大长度。dp代表到nums元素的最长递增序列,最后返回max。代码如下:


public class Solution {
    public int lengthOfLIS(int[] nums) {
        if(nums == null || nums.length == 0) return 0;
        int[] result = new int[nums.length];
        Arrays.fill(result, 1);
        int max = 1;
        for(int i = 1; i < result.length; i++) {
            for(int j = i; j > 0; j--) {
                if(nums[i] > nums[j - 1]) {
                    result[i] = Math.max(result[i], result[j - 1] + 1);
                }
            }
            if(result[i] > max) max = result[i];
        }
        return max;
    }
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。