tasks for today:
1. 300.最长递增子序列
2. 674.最长连续递增序列
3. 718.最长重复子数组
--------------------------------------------------------------------------
1. 300.最长递增子序列
In this practice, note the meaning of the dp list: which is: dp[i] signifies the longest ascending sequence that ends with nums[i].
The corresponding initialization of each entry on the dp list is set as 1.
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
if len(nums) == 1: return 1
dp = [1] * len(nums)
result = 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)
if dp[i] > result:
result = dp[i]
return result
2. 674.最长连续递增序列
Compared with last practice 300, the key difference is the requirment on "continuity" of the ascending sequence.
This reduces the trsaverse from two-fold loop to one loop, for each dp[i], there is no need to compare with each dp[j] + 1 with dp[i],
just need to figure out the relationship between dp[i] and dp[i-1].
class Solution:
def findLengthOfLCIS(self, nums: List[int]) -> int:
if len(nums) == 1: return 1
dp = [1] * len(nums)
result = 0
for i in range(1, len(nums)):
if nums[i] > nums[i-1]:
dp[i] = dp[i-1] + 1
if dp[i] > result:
result = dp[i]
return result
3. 718.最长重复子数组
Note: why there is no "else: dp[i][j] = dp[i-1][j-1]" for each "if", because, the way we define the dp table is "ending with the same nums1[i-1] and nums2[j-1]", so if nums1[i-1] != nums2[j-1], it is not right to do dp[i][j] = dp[i-1][j-1], it should remain 0, which reflected as not updated.
class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
if (len(nums1) == 1 and nums1[0] in nums2) or (len(nums2) == 1 and nums2[0] in nums1): return 1
if (len(nums1) == 1 and nums1[0] not in nums2) or (len(nums2) == 1 and nums2[0] not in nums1): return 0
dp = [[0] * (len(nums2) + 1) for _ in range(len(nums1) + 1)]
result = 0
for i in range(1, len(nums1)+1):
if nums1[i-1] == nums2[0]:
dp[i][1] = 1
for j in range(1, len(nums2)+1):
if nums1[0] == nums2[j-1]:
dp[1][j] = 1
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] + 1
if dp[i][j] > result:
result = dp[i][j]
return result