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(n^2) complexity.
用动态规划解决,时间复杂度为O(n^2)。创建一个动态数组dp[],维护一个变量max来记录最大长度。dp[i]代表到nums[i]元素的最长递增序列,最后返回max。代码如下:
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(n^2) complexity.
用动态规划解决,时间复杂度为O(n^2)。创建一个动态数组dp[],维护一个变量max来记录最大长度。dp[i]代表到nums[i]元素的最长递增序列,最后返回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;
}
}