代码随想录算法训练营Day 52 | 动态规划part13 | 300.最长递增子序列、674. 最长连续递增序列 、718. 最长重复子数组
文章目录
- 代码随想录算法训练营Day 52 | 动态规划part13 | 300.最长递增子序列、674. 最长连续递增序列 、718. 最长重复子数组
- 300.最长递增子序列
- 一、一维DP
- 674. 最长连续递增序列
- 一、贪心
- 二、动态规划
- 718. 最长重复子数组
- 一、二维动态规划
- 二、转换为字符串判断
- 三、一维DP
300.最长递增子序列
题目链接
一、一维DP
class Solution(object):def lengthOfLIS(self, nums):""":type nums: List[int]:rtype: int"""if len(nums) <= 1:return len(nums)# dp[i]表示i之前包括i的以nums[i]结尾的最长递增子序列的长度dp=[1]*len(nums)for i in range(1,len(nums)):for j in range(i):if nums[j]<nums[i]:dp[i]=max(dp[i],dp[j]+1)return dp[-1]
674. 最长连续递增序列
题目链接
一、贪心
class Solution(object):def findLengthOfLCIS(self, nums):""":type nums: List[int]:rtype: int"""maxcount =1count=1for i in range(len(nums)-1): if nums[i+1]>nums[i]:count +=1 else: #不连续,count从头开始count =1maxcount = max(maxcount,count)return maxcount
二、动态规划
class Solution(object):def findLengthOfLCIS(self, nums):""":type nums: List[int]:rtype: int"""if len(nums) <= 1:return len(nums)# 动态规划dp=[1]*len(nums)res =1for i in range(1,len(nums)):if nums[i-1]<nums[i]:dp[i]=dp[i-1]+1res = max(res,dp[i])return res
718. 最长重复子数组
题目链接
一、二维动态规划
class Solution(object):def findLength(self, nums1, nums2):""":type nums1: List[int]:type nums2: List[int]:rtype: int"""# dp[i][j] :以下标i - 1为结尾的A,和以下标j - 1为结尾的B,最长重复子数组长度为dp[i][j]。 (特别注意: “以下标i - 1为结尾的A” 标明一定是 以A[i-1]为结尾的字符串 )dp=[[0]*(len(nums2)+1) for _ in range(len(nums1)+1)]res=0# 全初始化为0# 递推公式for i in range(1,len(nums1)+1):for j in range(1,len(nums2)+1):if nums1[i-1]==nums2[j-1]:dp[i][j]=dp[i-1][j-1]+1res=max(res,dp[i][j])return res
二、转换为字符串判断
class Solution(object):def findLength(self, nums1, nums2):""":type nums1: List[int]:type nums2: List[int]:rtype: int"""s1 = "".join([chr(num) for num in nums1])s2 = "".join([chr(num) for num in nums2])n, res = len(s1), 0for i in range(n):for j in range(res+i+1, n+1):if s1[i:j] in s2:res = j - ielse:breakreturn res
三、一维DP
class Solution(object):def findLength(self, nums1, nums2):""":type nums1: List[int]:type nums2: List[int]:rtype: int"""# dp[i]:最长公共子数组长度dp=[0]*(len(nums2)+1)res=0for i in range(1,len(nums1)+1):for j in range(len(nums2), 0, -1):if nums1[i-1] == nums2[j-1]:dp[j] = dp[j-1] + 1else:dp[j]=0res=max(res,dp[j])return res