300. Longest Increasing Subsequence
文章目录
题目:
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?
解答:
public class Solution {
//State: f[i] is from 0 - i the longest length of increasing subsequence
//Function: f[i] = Max(f[i - k] + 1) if nums[i] > nums[k]
//Initialize: f[i] = 1;
//Result: f[nums.length - 1];
public int lengthOfLIS(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int[] f = new int[nums.length];
Arrays.fill(f, 1);
int max = 1;
for (int i = 1; i < nums.length; i++) {
for (int k = 0; k < i; k++) {
if (nums[i] > nums[k]) {
f[i] = Math.max(f[i], f[k] + 1);
}
}
max = Math.max(max, f[i]);
}
return max;
}
}

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论