码迷,mamicode.com
首页 > 其他好文 > 详细

动态规划_leetcode300(LIS)

时间:2019-03-17 13:57:41      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:ext   ali   next   not   动态规划   mem   经典   self   type   

#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)

动态规划_leetcode300(LIS)

标签:ext   ali   next   not   动态规划   mem   经典   self   type   

原文地址:https://www.cnblogs.com/lux-ace/p/10546562.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!