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;
}
}
原文地址:https://www.cnblogs.com/lawrenceSeattle/p/10276209.html
时间: 2024-12-14 23:21:28