当前位置:首页 > 编程笔记 > 正文
已解决

代码随想录算法训练营Day52 | 动态规划(13/17) LeetCode 300.最长递增子序列 674. 最长连续递增序列 718. 最长重复子数组

来自网友在路上 148848提问 提问时间:2023-09-20 17:41:26阅读次数: 48

最佳答案 问答题库488位专家为你答疑解惑

练习完股票买卖后,今天开始练习子序列问题。

第一题

300. Longest Increasing Subsequence

Given an integer array nums, return the length of the longest strictly increasing 

subsequence. (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.

continuous increasing subsequence is defined by two indices l and r (l < r) such that it is [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] and for each l <= i < rnums[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%的人还看了

猜你感兴趣

版权申明

本文"代码随想录算法训练营Day52 | 动态规划(13/17) LeetCode 300.最长递增子序列 674. 最长连续递增序列 718. 最长重复子数组":http://eshow365.cn/6-10130-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!