代码随想录算法训练营Day52 | 动态规划(13/17) LeetCode 300.最长递增子序列 674. 最长连续递增序列 718. 最长重复子数组
最佳答案 问答题库488位专家为你答疑解惑
练习完股票买卖后,今天开始练习子序列问题。
第一题
300. Longest Increasing Subsequence
Given an integer array
nums
, return the length of the longest strictly increasingsubsequence. (A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.)
借助动态规划五部曲:
- dp[i]的定义
- 本题中,正确定义dp数组的含义十分重要。
- dp[i]表示i之前包括i的以nums[i]结尾的最长递增子序列的长度
- 状态转移方程
- 位置i的最长升序子序列等于j从0到i-1各个位置的最长升序子序列 + 1 的最大值。
- 所以:if (nums[i] > nums[j]) dp[i] = max(dp[i], dp[j] + 1);
- 注意这里不是要dp[i] 与 dp[j] + 1进行比较,而是我们要取dp[j] + 1的最大值。
- dp[i]的初始化
- 每一个i,对应的dp[i](即最长递增子序列)起始大小至少都是1.
- 确定遍历顺序
- dp[i] 是有0到i-1各个位置的最长递增子序列 推导而来,那么遍历i一定是从前向后遍历。
- 举例推导dp数组
class Solution:def lengthOfLIS(self, nums: List[int]) -> int:if len(nums) <= 1:return len(nums)dp = [1] * len(nums)result = 1for i in range(1, len(nums)):for j in range(0, i):if nums[i] > nums[j]:dp[i] = max(dp[i], dp[j] + 1)result = max(result, dp[i]) return result
第二题
674. Longest Continuous Increasing Subsequence
Given an unsorted array of integers
nums
, return the length of the longest continuous increasing subsequence (i.e. subarray). The subsequence must be strictly increasing.A continuous increasing subsequence is defined by two indices
l
andr
(l < r
) such that it is[nums[l], nums[l + 1], ..., nums[r - 1], nums[r]]
and for eachl <= i < r
,nums[i] < nums[i + 1]
.
如果 nums[i] > nums[i - 1],那么以 i 为结尾的连续递增的子序列长度 一定等于 以i - 1为结尾的连续递增的子序列长度 + 1 。
即:dp[i] = dp[i - 1] + 1;
class Solution:def findLengthOfLCIS(self, nums: List[int]) -> int:if len(nums) == 0:return 0result = 1dp = [1] * len(nums)for i in range(len(nums)-1):if nums[i+1] > nums[i]: #连续记录dp[i+1] = dp[i] + 1result = max(result, dp[i+1])return result
99%的人还看了
相似问题
- 【Django-DRF用法】多年积累md笔记,第3篇:Django-DRF的序列化和反序列化详解
- 【Java 进阶篇】JavaScript JSON 语法入门:轻松理解数据的序列化和反序列化
- 【python学习】基础篇-常用模块-pickle模块:序列化和反序列化
- ZC序列理论学习及仿真
- 时间序列预测实战(十七)PyTorch实现LSTM-GRU模型长期预测并可视化结果(附代码+数据集+详细讲解)
- 代码随想录算法训练营第二十九天| 491 递增子序列 46 全排列
- 最长递增子序列
- 深入解析序列模型:全面阐释 RNN、LSTM 与 Seq2Seq 的秘密
- c#Nettonsoft.net库常用的方法json序列化反序列化
- 基于C#实现最长公共子序列
猜你感兴趣
版权申明
本文"代码随想录算法训练营Day52 | 动态规划(13/17) LeetCode 300.最长递增子序列 674. 最长连续递增序列 718. 最长重复子数组":http://eshow365.cn/6-10130-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!
- 上一篇: 【系统美化】快速打开鼠标样式切换的对话框
- 下一篇: 五个很实用的IDEA使用技巧