if (nums[i] > nums[j]) dp[i] = max(dp[i], dp[j] + 1)
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
dp = [1 for _ in range(len(nums))]
res = 0
for i in range(len(nums)):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
res = max(res, dp[i])
return res
O(n^2)
O(n)
本题和上题类似,区别在于连续,所以在遍历的时候只需要比较nums[i]和nums[i-1]即可。
递推公式为 if (nums[i] > nums[i - 1]) dp[i] = max(dp[i], dp[i - 1] + 1)
贪心
这道题目也可以用贪心来做,也就是遇到nums[i] > nums[i - 1]的情况,count就++,否则count为1,记录count的最大值就可以了。
class Solution:
def findLengthOfLCIS(self, nums: List[int]) -> int:
dp = [1 for _ in range(len(nums))]
res = 1
for i in range(1, len(nums)):
if nums[i] > nums[i - 1]:
dp[i] = max(dp[i], dp[i - 1] + 1)
res = max(res, dp[i])
return res
O(n)
O(n)
寻找两个数组中最长的 公共 连续子序列。
dp[i][j] = dp[i - 1][j - 1] + 1
dp[i][j] = dp[i - 1][j - 1] + 1
, 所以dp[i][0] 和dp[0][j]初始化为0。class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
dp = [[0] * (1 + len(nums1)) for _ in range(len(nums2) + 1)]
res = 0
for i in range(1, len(nums2) + 1):
for j in range(1, len(nums1) + 1):
if nums2[i - 1] == nums1[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
res = max(res, dp[i][j])
return res
O(n × m)
,n 为A长度,m为B长度O(n × m)