300. 最长递增子序列
原文链接:https://blog.csdn.net/qq_39355828/article/details/120776896 (opens new window)
- 最长递增子序列
给你一个整数数组 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 。
示例 2:
输入:nums = [0,1,0,3,2,3]
输出:4
import org.junit.Test;
public class test300 {
public int lengthOfLIS(int[] nums) {
//定义动态规划数组
int[]dp=new int[nums.length];
//初始化数组
for(int i=0;i<dp.length;i++)
dp[i]=1;
for(int i=1;i<nums.length;i++)
{
for(int j=0;j<i;j++)
{
if(nums[i]>nums[j])
dp[i]=Math.max(dp[i],dp[j]+1);//计算从0-i-1,计算当前值小的数字
}
}
int max=1;
for(int i=0;i<dp.length;i++)
{
max=Math.max(max,dp[i]);
}
return max;
}
@Test
public void test()
{
int[] nu=new int[]{10,9,2,5,3,7,101,18};
System.out.println(lengthOfLIS(nu));
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
编辑 (opens new window)
上次更新: 2026/08/11, 13:36:18