python
class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
dp = [0] * len(nums)
dp[0], dp[1] = nums[0], max(nums[0], nums[1])
for i in range(2, len(nums)):
dp[i] = max(dp[i - 1], dp[i - 2] + nums[i])
return dp[len(nums) - 1]
python
class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) <= 2:
return max(nums)
def get_dp(nums):
if len(nums) == 1:
return nums[0]
n = len(nums)
dp = [0] * n
dp[0], dp[1] = nums[0], max(nums[0], nums[1])
for i in range(2, n):
dp[i] = max(dp[i - 1], dp[i - 2] + nums[i])
return dp[n - 1]
return max(get_dp(nums[:-1]), get_dp(nums[1:]))
python
# Definition for a binary tree node.
# 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: Optional[TreeNode]) -> int:
return max(self.traversal(root))
def traversal(self, node):
if not node:
return (0, 0)
left = self.traversal(node.left)
right = self.traversal(node.right)
val_0 = max(left) + max(right)
val_1 = node.val + left[0] + right[0]
return val_0, val_1
这题目自己想不出来,但是讲过之后,看了代码知道了意思,但是过一段时间,恐怕会忘。