2025-04-17 12:08:47 +08:00
|
|
|
|
package dynamic_programming;
|
|
|
|
|
|
|
|
|
|
import java.util.Arrays;
|
|
|
|
|
import java.util.PriorityQueue;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 题目: 300. 最长递增子序列 (lengthOfLIS)
|
|
|
|
|
* 描述:给你一个整数数组 nums ,找到其中最长严格递增子序列的长度。
|
|
|
|
|
* 子序列 是由数组派生而来的序列,删除(或不删除)数组中的元素而不改变其余元素的顺序。例如,[3,6,2,7] 是数组 [0,3,1,6,2,2,7] 的子序列。
|
|
|
|
|
|
|
|
|
|
* 示例 1:
|
|
|
|
|
输入:nums = [10,9,2,5,3,7,101,18]
|
|
|
|
|
输出:4
|
|
|
|
|
解释:最长递增子序列是 [2,3,7,101],因此长度为 4 。
|
|
|
|
|
|
|
|
|
|
* 链接:https://leetcode.cn/problems/longest-increasing-subsequence/
|
|
|
|
|
*/
|
|
|
|
|
//没做出来
|
2025-07-25 18:23:29 +08:00
|
|
|
|
//二刷会做
|
2025-04-17 12:08:47 +08:00
|
|
|
|
public class LengthOfLIS {
|
2025-07-25 18:23:29 +08:00
|
|
|
|
public int lengthOfLIS1(int[] nums) {
|
|
|
|
|
int length=nums.length;
|
|
|
|
|
int[] dp=new int[length];
|
|
|
|
|
int MMax=1;
|
|
|
|
|
Arrays.fill(dp,1);
|
|
|
|
|
for (int i = 0; i < length; i++) {
|
|
|
|
|
for (int j = 0; j < i; j++) {
|
|
|
|
|
if(nums[i]>nums[j]) {
|
|
|
|
|
dp[i] = Math.max(dp[i], dp[j] + 1);
|
|
|
|
|
MMax=Math.max(MMax,dp[i]);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return MMax;
|
|
|
|
|
}
|
|
|
|
|
|
2025-04-17 12:08:47 +08:00
|
|
|
|
public int lengthOfLIS(int[] nums) {
|
|
|
|
|
if(nums.length == 0) return 0;
|
|
|
|
|
int[] dp = new int[nums.length];
|
|
|
|
|
int res = 0;
|
|
|
|
|
Arrays.fill(dp, 1);
|
|
|
|
|
for(int i = 0; i < nums.length; i++) {
|
|
|
|
|
for(int j = 0; j < i; j++) {
|
|
|
|
|
if(nums[j] < nums[i]) dp[i] = Math.max(dp[i], dp[j] + 1);
|
|
|
|
|
}
|
|
|
|
|
res = Math.max(res, dp[i]);
|
|
|
|
|
}
|
|
|
|
|
return res;
|
|
|
|
|
}
|
|
|
|
|
}
|