Leetcode - 300 Longest Increasing Subsequence (Medium)
题目描述:给定无序的整数数组,找到最长上升子序列的长度。
Input: [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
解题思路:定义状态 dp[i]
表示从数组的头部到第 i 个元素的最长商城子序列长度。dp[i]
为 i 之前的最大上升子序列的长度加 1, dp[i] = max{dp[j]} + 1
,最终的结果是所有 dp[i]
的最大值。在求解的过程中,需要计算第 i 个元素之前元素的最大值,可以使用二分查找的方法,将时间复杂度优化为 O(nlogn)。
public int lengthOfLIS(int[] nums) {
if(nums == null || nums.length == 0) return 0;
int[] dp = new int[nums.length];
dp[0] = 1;
int maxAns = 1;
for(int i = 1; i < dp.length; i++){
int maxVal = 0;
for(int j = 0; j < i; j++){
if(nums[i] > nums[j]){
maxVal = Math.max(maxVal, dp[j]);
}
}
dp[i] = maxVal + 1;
maxAns = Math.max(maxAns, dp[i]);
}
return maxAns;
}