tasks for today:(打家劫舍专题)
1. 198.打家劫舍
2. 213.打家劫舍II
3. 337.打家劫舍III
----------------------------------------------------------------------------
1. 198.打家劫舍
the key is the recursive equation and the way to initialize the dp list, also the special circumstance.
dp[i] = max(nums[i] + dp[i-2], dp[i-1]);
dp[0] = nums[0], dp[1] = max(nums[0], nums[1]);
if len(nums) == 1: return nums[0]; if len(nums) == 2: return max(nums);
class Solution:
def rob(self, nums: List[int]) -> int:
m = len(nums)
if m == 1: return nums[0]
if m == 2: return max(nums)
dp = [0] * m
dp[0] = nums[0]
dp[1] = max(nums[0], nums[1])
for i in range(2, m):
dp[i] = max(nums[i] + dp[i-2], dp[i-1])
return dp[-1]
2. 213.打家劫舍II
In this practice, the key difference is that the head and tail are ajacent, so this can be break down into two problem, including one list excluding the head and another list excluding the tail one, then find the max value of this two subproblem.
class Solution:
def rob(self, nums: List[int]) -> int:
# two conditions should be considered
# 1. do not include last one
# 2. do not include first one
if len(nums) == 1: return nums[0]
nums1 = nums[:-1]
nums2 = nums[1:]
return max(self.check(nums1), self.check(nums2))
def check(self, moneylist: List[int]) -> int:
m = len(moneylist)
if m == 0: return 0
if m == 1: return moneylist[0]
if m == 2: return max(moneylist)
dp = [0] * m
dp[0] = moneylist[0]
dp[1] = max(moneylist[0], moneylist[1])
for i in range(2, m):
dp[i] = max(dp[i-2]+moneylist[i], dp[i-1])
return dp[-1]
3. 337.打家劫舍III
In this practice, being combined with binary tree, first, we determine that the traverse order should be post-traverse;
for each node, there should be an associated dp list with two values [val_0, val_1], which represent [“the max value when not stealing this node”, "the max value when stealing this node"].
Actually, the recursive function (3-step recursive rules) in this practice is essentially the traverse process in dp (5-step dp rules).
# 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:
dp = self.traversenode(root)
return max(dp)
def traversenode(self, node: Optional[TreeNode]) -> List[int]:
if not node:
return [0, 0]
left = self.traversenode(node.left)
right = self.traversenode(node.right)
# do not steal this node
val_0 = max(left) + max(right)
# steal this node
val_1 = node.val + left[0] + right[0]
return [val_0, val_1]