day43-dynamic programming-part10-8.14

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

  • 8
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值