赞
踩
# 198.打家劫舍 class Solution: def rob(self, nums): if len(nums) == 0: return 0 if len(nums) == 1: return nums[0] dp = [0] * len(nums) dp[0] = nums[0] dp[1] = max(nums[0], nums[1]) for i in range(2, len(nums)): dp[i] = max(dp[i-2] + nums[i], dp[i-1]) return dp[-1] # 213.打家劫舍II class Solution: def rob(self, nums): if len(nums) == 1: return nums[0] v1 = self.roblist(nums[1:]) v2 = self.roblist(nums[:-1]) return max(v1, v2) def robRange(self, nums): l = len(nums) dp = [0] * l dp[0] = nums[0] for i in range(1, l): if i == 1: dp[i] = max(dp[i-1], nums[i]) else: dp[i] = max(dp[i-1], dp[i-2] + nums[i]) return dp[-1] # 337.打家劫舍III class TreeNode: def __init__(self, val = 0, left = None, right = None): self.val = val self.left = left self.right = right class Solution: def rob(self, root): dp = self.traversal(root) return max(dp) def traversal(self, node): if not node: return (0, 0) left = self.traversal(node.left) right = self.traversal(node.right) val_0 = max(left[0], left[1]) + max(right[0], right[1]) val_1 = node.val + left[0] + right[0] return (val_0, val_1)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。