动态规划_leetcode300(LIS)

Posted AceKo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了动态规划_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)

以上是关于动态规划_leetcode300(LIS)的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode刷题 --动态规划练习题 --300 最长上升子序列

LeetCode 第 58 场力扣夜喵双周赛(动态规划马拉车算法,前后缀处理)/ 第 253 场力扣周赛(贪心,LIS)

动态规划-LIS最长上升子序列

LeetCode刷题 最长递增子序列

动态规划 | 对输入进行hash处理的LIS 1045

动态规划模板1|LIS最长上升子序列