动态规划,house robber系列三道题:
第一道题:
没有限制,因此直接用动态规划就可以做,这里有两种方式:
第一种,空间省,时间稍微多一些: 只有两个数值,lastTotal 和reTotal来记录获得的金钱多少
class Solution:
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums)<1:
return 0
if len(nums)<2:
return nums[0]
lastTotal = 0
reTotal = nums[0]
for i in range(1,len(nums)):
lastTotal,reTotal =reTotal,max(reTotal,lastTotal+nums[i])
return reTotal
第二种,时间快,空间上采用了数值,用一个和nums等长的数组来记录这些值:
class Solution:
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums)==0:
return 0
elif len(nums)<2:
return nums[0]
money = [0]*len(nums)
money[0],money[1] = nums[0],max(nums[0],nums[1])
for i in range(2,len(nums)):
money[i] = max(nums[i]+money[i-2],money[i-1])
return money[-1]
第二道题:
开始有了限制,把商店围城了一个圈,那么分析完,得到的结论就是,只要不同时抢劫第一家和最后一家店即可。
这里采用了分类讨论,两种情况,第一种,抢劫范围为第一家到倒数第二家店。第二种情况,抢劫范围为第二家到最后一家店。然后比较,返回两者之间的最大值。
同样的,也有可以采用第一道题的空间时间策略,分类讨论即可。
class Solution:
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums)==0:
return 0
elif len(nums) == 1:
return nums[0]
lastTotal = 0
retotal = nums[0]
for i in range(1,len(nums)-1):
lastTotal,retotal = retotal,max(retotal,lastTotal+nums[i])
lastTotal2 = 0
retotal2 = nums[1]
for i in range(2,len(nums)):
lastTotal2,retotal2 = retotal2,max(retotal2,lastTotal2+nums[i])
print(retotal)
print(retotal2)
return max(retotal,retotal2)
class Solution:
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums)==0:
return 0
elif len(nums) ==1:
return nums[0]
elif len(nums) == 2:
return max(nums[0],nums[1])
elif len(nums) == 3:
return max(nums[0],nums[1],nums[2])
total = [0]*(len(nums)-1)
total2 = [0]*(len(nums))
total[0] = nums[0]
total[1] = max(nums[0],nums[1])
for i in range(2,len(nums)-1):
total[i] = max(total[i-2]+nums[i],total[i-1])
total2[1] = nums[1]
total2[2] = max(nums[1],nums[2])
for i in range(3,len(nums)):
total2[i] = max(total2[i-2]+nums[i],total2[i-1])
return max(total[-1],total2[-1])
第三道题:
二叉树的运用,这里最原先的想法是用root.val+root.left.left.val+root.left.right+root.right.left.val+root.right.right与root.left.val+root.right.val对比,但是运行时间耗时很长,迭代不简洁,看了别人的代码,想法是每一个节点,记录两种情况,抢劫当前节点和不抢劫当前节点获得的钱数,这样,每次迭代的函数处理的节点就只有三个,三个节点分别为根节点和两个叶子节点:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def dfs(root):
if not root: return (0,0)
pickleft,nopickleft = dfs(root.left)
pickright,nopickright = dfs(root.right)
renPick = nopickleft +nopickright +root.val
renNopick = max(pickleft,nopickleft) + max(pickright,nopickright)
return renPick,renNopick
return max(dfs(root)[0],dfs(root)[1])