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;
}
}
本文介绍了一种使用动态规划方法解决寻找无序整数数组中最长递增子序列长度的问题。通过创建动态数组dp并维护变量max来记录最大长度,最终返回max作为结果。
4327

被折叠的 条评论
为什么被折叠?



