334遞增的三元子序列

from typing import List# 這道題我是用動態規劃的方法來作的,# 時間複雜度是O(n~2)空間複雜度是O(n)。# 定義一個列表,其中用來存放當前數比前面幾個數遞增大。class Solution:    def increasingTriplet(self, nums: List[int]) -> bool:        # 若是列表沒喲三個數,直接返回False        if len(nums) < 3 :return False        # 定義一個列表,用來表示動態方程,這裏將他們的初始值都設置成1        dp = [1 for i in range(len(nums))]        # 進行遍歷        for index1 in range(1,len(nums)):            # 把當前數都和前邊的數做比較,若是比某一個數大,就在它的基礎上加上一            for index2 in range(0,index1):                # 這裏dp上每個位置,都表示這個數比前邊幾個遞增數大。                if nums[index1] > nums[index2]:                    dp[index1] = max(dp[index1],dp[index2] + 1)                    #若是有遞增三元組,就返回真,這樣後邊的就不用了遍歷了                    if dp[index1] >= 3:return True        # 所有遍歷完成,沒有退出函數,就返回false        else:            return FalseA = Solution()print(A.increasingTriplet([1,2,3,4,5]))print(A.increasingTriplet([4,5,4,4]))print(A.increasingTriplet([1,2,-10,-8,-7]))
相關文章
相關標籤/搜索