300. 最长递增子序列
动规:
妥妥O(n^2)的动规
dp[i]表示以i结尾的LIS,初始化都为1。
当nums[i + 1]加入进来,就要去找0-i中比nums[i + 1]小的nums[j], 并且更新dp[i+1]为dp[j] + 1和他自己较大的一个。
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
n = len(nums)
dp = [1] * (n + 1)
for i in range(1, n):
for j in range(i - 1, -1, -1):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
贪心:(看题解)
维护一个数组tails,其中tails[i]存储长度为 i+1 的所有递增子序列的最小结尾元素。遍历nums数组,将每个元素num二分插入到tails中。tails的长度即是到当前遍历位置的LIS的元素个数。
通过遍历更新让tail[i]更小,给后续寻找更长的LIS挪出位置。
class Solution:
def lengthOfLIS(self, nums):
def binary_search(sub, val):
left, right = 0, len(sub) - 1
while left <= right:
mid = left + (right - left) // 2
if sub[mid] < val:
left = mid + 1
else:
right = mid - 1
return left
tails = []
for num in nums:
pos = binary_search(tails, num)
if pos == len(tails):
tails.append(num)
else:
tails[pos] = num
return len(tails)
674. 最长连续递增序列
动规:
只有nums[i]比nums[i - 1]大的时候,LCIS才会增加。
class Solution:
def findLengthOfLCIS(self, nums: List[int]) -> int:
n = len(nums)
dp = [1] * n
for i in range(1, n):
if nums[i] > nums[i - 1]:
dp[i] = dp[i - 1] + 1
return max(dp)
贪心:
class Solution:
def findLengthOfLCIS(self, nums: List[int]) -> int:
n = len(nums)
res = 1
count = 1
for i in range(1, n):
if nums[i] > nums[i - 1]:
count += 1
else:
count = 1
res = count if count > res else res
return res
718. 最长重复子数组
class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
n1, n2 = len(nums1), len(nums2)
dp = [[0] * (n2 + 1) for _ in range(n1 + 1)]
max_length = 0
for i in range(1, n1 + 1):
for j in range(1, n2 + 1):
if nums1[i - 1] == nums2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
max_length = max(max_length, dp[i][j])
return max_length
今日总结:
今天感觉三道算入门级的...