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

[LintCode]76. Longest Increasing Subsequence

时间:2019-01-16 13:18:18      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:math   turn   lin   []   for   longest   ==   possible   max   

Given a sequence of integers, find the longest increasing subsequence (LIS).

You code should return the length of the LIS.

Example
For [5, 4, 1, 2, 3], the LIS is [1, 2, 3], return 3
For [4, 2, 4, 5, 3, 7], the LIS is [2, 4, 5, 7], return 4

Challenge
Time complexity O(n^2) or O(nlogn)

Clarification
What‘s the definition of longest increasing subsequence?

The longest increasing subsequence problem is to find a subsequence of a given sequence in which the subsequence‘s elements are in sorted order, lowest to highest, and in which the subsequence is as long as possible. This subsequence is not necessarily contiguous, or unique.
public class Solution {
    /**
     * @param nums: An integer array
     * @return: The length of LIS (longest increasing subsequence)
     */
     
    public int longestIncreasingSubsequence(int[] nums) {
        if(nums == null || nums.length <= 0) {
            return 0;
        }
        int len = nums.length;
        int[] cnt = new int[len];
        int res = 1;
        cnt[0] = 1;
        for(int i = 1; i < len; i++) {
            cnt[i] = 1;  // 最少的也是1个,初始化的时候容易初始化为0
            for(int j = 0; j < i; j++) {
                if(nums[j] < nums[i]) {
                    if(cnt[i] < cnt[j] + 1) {
                        cnt[i] = cnt[j]+1;
                        res = Math.max(res, cnt[i]);
                    }
                }
            }
        }
        return res;
    }
}

[LintCode]76. Longest Increasing Subsequence

标签:math   turn   lin   []   for   longest   ==   possible   max   

原文地址:https://www.cnblogs.com/lawrenceSeattle/p/10276209.html

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