练习完股票买卖后,今天开始练习子序列问题。
第一题
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 = 1
for 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 0
result = 1
dp = [1] * len(nums)
for i in range(len(nums)-1):
if nums[i+1] > nums[i]: #连续记录
dp[i+1] = dp[i] + 1
result = max(result, dp[i+1])
return result