[LintCode]76. Longest Increasing Subsequence
Posted lawrenceseattle
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LintCode]76. Longest Increasing Subsequence相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章
LintCode Longest Common Subsequence
LintCode Longest Common Substring
lintcode-medium-Longest Increasing Subsequence
lintcode-medium-Longest Consecutive Sequence
[Lintcode]124. Longest Consecutive Sequence/[Leetcode]128. Longest Consecutive Sequence