House Robber III
https://leetcode.com/problems/house-robber-iii/
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the “root.” Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that “all houses in this place forms a binary tree”. It will automatically contact the police if two directly-linked houses were broken into on the same night.
Determine the maximum amount of money the thief can rob tonight without alerting the police.
Example 1:
3
/ \
2 3
\ \
3 1
Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
3
/ \
4 5
/ \ \
1 3 1
Maximum amount of money the thief can rob = 4 + 5 = 9.
Recursive function
If we rob a node
, then all its children can’t be robbed due to alarm but the children of its children are available to rob.
If we define rob(node)
as the max amount of money the thief can get if he robs this tree and node
is the root of the tree, then
|
|
Dynamic Programming
The above function works. However, there’s overlaps among the functions calls since this is a DFS
kind of recursive calls. I can use a cache to store the value to avoid re-computation.
Use a Map
to cache the result of node
.
|
|
Alternative solution
For a TreeNode root
, only 2 possible way to do with it: either rob this root or not.
We can use a int[2]
to represent the two scenarios. [0]
means the max amount of money we get not to rob the node, [1]
means the max money we get if we rob.
|
|