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)
  • 相关阅读:
    JS—图片压缩上传(单张)
    vue 使用jssdk分享
    微信JS-SDK选择图片遇到的坑
    手把手教你实现一个微信自动回复机器人
    SSH实现远程控制
    使用Apache服务部署静态网站
    Rhel7安装及网卡、yum、vmtools配置和修改主机名
    基础工具之消息队列、线程池、缓冲区抽象、事件循环和日志实现
    I/O多路复用方案
    Java按字节截取字符串(GBK编码、UTF-8编码实现)
  • 原文地址:https://www.cnblogs.com/lux-ace/p/10546562.html
Copyright © 2011-2022 走看看