数据结构与算法:动态规划dp:子序列相关力扣题(上):300. 最长递增子序列、674.最长连续递增序列

300. 最长递增子序列

class Solution:
    def lengthOfLIS(self, nums: List[int]) -> int:
        length = len(nums)
        if length==1:
            return 1
        # dp[i]指的是以nums[i]为结尾的最长递增子序列的长度。
        dp = [1] * length
        mmax = 1
        for i in range(1, length):
            for j in range(i):
                if nums[i] > nums[j]:
                    dp[i] = max(dp[j]+1,dp[i])
            mmax = max(dp[i], mmax)
        return mmax

674.最长连续递增序列

1.双指针

class Solution:
    def findLengthOfLCIS(self, nums: List[int]) -> int:
        length = len(nums)
        if length == 1:
            return 1
        # 双指针解法
        mmax = 1
        i = 0
        while i < length-1:
            temp = 1
            j = i + 1
            while j < length and nums[j]>nums[j-1]:
                temp += 1
                j += 1
            i = j
            mmax = max(mmax,temp)
        return mmax

效率:3ms,击败77.69%

2.动态规划

class Solution:
    def findLengthOfLCIS(self, nums: List[int]) -> int:
        length = len(nums)
        if length == 1:
            return 1
        mmax = 1
        dp = [1] * length
        for i in range(1, length):
            if nums[i] > nums[i-1]:
                dp[i] = dp[i-1]+1
            mmax = max(dp[i], mmax)
        return mmax

效率:7ms,击败24.83%

你可能感兴趣的:(数据结构与算法,LeetCode,动态规划,leetcode,算法,子序列,力扣,dp,数据结构)