class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
if len(nums) <= 1:
return len(nums)
# dp 数组代表以 nums[i] 结尾的最长递增子序列长度为 dp[i]
dp = [1] * len(nums)
res = 1
for i in range(1, len(nums)):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
res = max(dp[i], res)
return res
674. 最长连续递增序列
1、贪心法
class Solution:
def findLengthOfLCIS(self, nums: List[int]) -> int:
if len(nums) <= 1:
return len(nums)
max_res = 1
cur = 1
for i in range(1, len(nums)):
if nums[i] > nums[i-1]:
cur += 1
else:
cur = 1
max_res = max(max_res, cur)
return max_res
2、动态规划法
class Solution:
def findLengthOfLCIS(self, nums: List[int]) -> int:
if len(nums) <= 1:
return len(nums)
# dp 数组代表 nums[i] 结尾的最长连续递增子序列为 dp[i]
dp = [1] * len(nums)
res = 1
for i in range(1, len(nums)):
if nums[i] > nums[i-1]:
dp[i] = dp[i-1] + 1
res = max(dp[i], res)
return res
class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
# dp 数组代表以 i-1 结尾的 nums1 数组和 j-1 结尾的 nums2 数组的最长公共子数组长度为 dp[i][j]
n = len(nums1)
m = len(nums2)
dp = [[0] * (m+1) for _ in range(n+1)]
res = 0
for i in range(1, n+1):
for j in range(1, m+1):
if nums1[i-1] == nums2[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
res = max(res, dp[i][j])
return res
标签:nums,int,res,递增,max,序列,最长,dp
From: https://www.cnblogs.com/yixff/p/17868640.html