zoukankan      html  css  js  c++  java
  • 动态规划_leetcode300(LIS)

    #coding=utf-8

    # 递归1
    #
    #
    # 选与不选 经典的组合问题

    class Solution1(object):
    def lengthOfLIS(self, nums):
    """
    :type nums: List[int]
    :rtype: int
    """
    self.res = 0

    if not nums :
    return 0

    ans = []
    self.getLIS(nums,0,ans)

    return self.res

    def getLIS(self,nums,index,ans):

    if index == len(nums):
    if self.isLIS(ans):
    self.res = max(self.res,len(ans))
    return


    ans.append(nums[index])
    self.getLIS(nums,index+1,ans)
    ans.pop()
    self.getLIS(nums,index+1,ans)

    def isLIS(self,ans):
    if not ans:
    return False

    if len(ans) == 1:
    return True

    pre = 0
    next = 1

    while next < len(ans):
    if ans[pre] > ans[next]:
    return False
    else:
    pre += 1
    next += 1

    return True



    # s = Solution1()
    # nums1 = [10, 9, 2, 5, 3, 7, 101, 18]
    # print s.lengthOfLIS(nums1)



    # 递归2 生成所有的组合
    class Solution2(object):
    def lengthOfLIS(self, nums):
    """
    :type nums: List[int]
    :rtype: int
    """

    self.res = 0
    self.getCombination(nums,0,[])

    return self.res

    def isLIS(self,ans):
    if not ans:
    return False

    if len(ans) == 1:
    return True

    pre = 0
    next = 1

    while next < len(ans):
    if ans[pre] > ans[next]:
    return False
    else:
    pre += 1
    next += 1

    return True

    def getCombination(self,nums,index,ans):

    if self.isLIS(ans):
    self.res = max(self.res,len(ans))
    for i in range(index,len(nums)):
    ans.append(nums[i])
    self.getCombination(nums,i+1,ans)
    ans.pop()


    # s = Solution2()
    # nums1 = [10, 9, 2, 5, 3, 7, 101, 18]
    # nums2 = [1,2,3]
    # print s.lengthOfLIS(nums1)


    # 动态规划
    class Solution3(object):
    def lengthOfLIS(self, nums):
    """
    :type nums: List[int]
    :rtype: int
    """


    memo = [1 for i in range(len(nums)) ]

    for i in range(len(nums)):
    for j in range(i): if nums[i] > nums[j]: memo[i] = max(memo[i],memo[j]+1) res = 0 for i in range(len(nums)): res = max(res,memo[i]) return ress = Solution3()nums1 = [10, 9, 2, 5, 3, 7, 101, 18]nums2 = [1,2,3]print s.lengthOfLIS(nums1)
  • 相关阅读:
    前缀和
    B. Ilya and Queries
    BZOJ1652 [Usaco2006 Feb]Treats for the Cows
    NOIP2014提高组 酱油记
    NOIP初赛 BLESS ALL!
    BZOJ1096 [ZJOI2007]仓库建设
    BZOJ1036 [ZJOI2008]树的统计Count
    BZOJ1030 [JSOI2007]文本生成器
    BZOJ2749 [HAOI2012]外星人
    BZOJ1093 [ZJOI2007]最大半连通子图
  • 原文地址:https://www.cnblogs.com/lux-ace/p/10546562.html
Copyright © 2011-2022 走看看