File tree Expand file tree Collapse file tree 3 files changed +69
-1
lines changed Expand file tree Collapse file tree 3 files changed +69
-1
lines changed Original file line number Diff line number Diff line change 77
77
560. 和为 K 的子数组
78
78
589. N叉树的前序遍历
79
79
617. 合并二叉树
80
+ 674. 最长连续递增序列
80
81
695. 岛屿的最大面积
81
82
698. 划分为k个相等的子集
82
83
714. 买卖股票的最佳时机含手续费
Original file line number Diff line number Diff line change 2
2
3
3
4
4
/*
5
+ 题目简化:求数组的最长递增子序列的长度
5
6
1、定义dp数组:dp[i] 表示以索引i的元素结尾的最长递增子序列的长度
6
7
2、状态转移方程:if (nums[i] > nums[j]) dp[i] = Math.max(dp[i], dp[j] + 1);
7
- 位置i的最长递增子序列长度 等于j从0到i-1各个位置的 最长递增子序列加1的 最大值
8
+ 位置i的最长递增子序列长度 等于j从0到i-1各个位置的 最长递增子序列长度加1的 最大值
8
9
3、初始化:dp[i] = 1 表示每一个位置i的递增子序列的长度至少是1
9
10
4、遍历dp数组填表:第一个for循环遍历dp数组的未知位置,第二个for循环遍历dp数组的已知位置,根据状态转移方程获取已知结果计算未知结果
10
11
5、返回结果:遍历时比较每个位置结尾时的最长递增子序列的长度,并记录最大值,最后返回最大值
Original file line number Diff line number Diff line change
1
+ // 674. 最长连续递增序列
2
+
3
+
4
+ /*
5
+ 动态规划:
6
+ 题目简化:求数组的最长连续递增子序列的长度
7
+ 1、定义dp数组:dp[i] 表示以索引i的元素结尾的最长连续递增子序列的长度
8
+ 2、初始化:dp[i] = 1 表示每一个位置i的连续递增子序列的长度至少是1
9
+ 3、状态转移方程:if (nums[i] > nums[i - 1]) dp[i] = dp[i - 1] + 1;
10
+ 位置i的最长连续递增子序列长度 等于前一位置的最长连续递增子序列长度加1
11
+ 4、遍历dp数组填表:一个for循环遍历dp数组的未知位置,根据状态转移方程获取已知结果计算未知结果
12
+ 5、返回结果:遍历时比较每个位置结尾时的最长连续递增子序列的长度,并记录最大值,最后返回最大值
13
+ */
14
+ class Solution {
15
+ public int findLengthOfLCIS (int [] nums ) {
16
+ int n = nums .length ;
17
+ int [] dp = new int [n ];
18
+ Arrays .fill (dp , 1 );
19
+ int res = 1 ;
20
+ for (int i = 1 ; i < n ; i ++) {
21
+ if (nums [i ] > nums [i - 1 ]) {
22
+ dp [i ] = dp [i - 1 ] + 1 ;
23
+ res = Math .max (res , dp [i ]);
24
+ }
25
+ }
26
+ return res ;
27
+ }
28
+ }
29
+
30
+
31
+ /*
32
+ 贪心:双指针,遍历数组,记录起始位置,当前元素比前一元素大时 计算连续递增子序列的长度 并保存最大值,否则将当前位置重新作为起始位置,最终返回最长连续递增子序列的长度
33
+ */
34
+ class Solution {
35
+ public int findLengthOfLCIS (int [] nums ) {
36
+ int start = 0 ;
37
+ int res = 1 ;
38
+ for (int i = 1 ; i < nums .length ; i ++) {
39
+ if (nums [i ] > nums [i - 1 ]) {
40
+ res = Math .max (res , i - start + 1 );
41
+ } else {
42
+ start = i ;
43
+ }
44
+ }
45
+ return res ;
46
+ }
47
+ }
48
+
49
+
50
+ /*
51
+ 贪心:变量计数
52
+ */
53
+ class Solution {
54
+ public int findLengthOfLCIS (int [] nums ) {
55
+ int count = 1 ;
56
+ int res = 1 ;
57
+ for (int i = 1 ; i < nums .length ; i ++) {
58
+ if (nums [i ] > nums [i - 1 ]) {
59
+ res = Math .max (res , ++count );
60
+ } else {
61
+ count = 1 ;
62
+ }
63
+ }
64
+ return res ;
65
+ }
66
+ }
You can’t perform that action at this time.
0 commit comments