2025-07-25 18:23:29 +08:00

51 lines
1.5 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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/
*/
//没做出来
//二刷会做
public class LengthOfLIS {
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;
}
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;
}
}