2018年6月3日 星期日

[LeetCode] 337. House Robber III

轉自LeetCode

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.

<Solution>

198. House Robber 的衍生題,資料結構變成 binary tree

想法如下
  • 每個節點都有選與不選兩種狀況。如果該節點被選,則它的兩個子節點就不能被選;反之,他兩個子節點可以被選
  • 樹的資料結構,加上有選與不選的狀況,使用 recursive 來解
  • 回傳一個 int[],第一個位置放包含該節點的最佳解,第二個位置放不包含該節點的最佳解
code 如下

Java(參考解法)

kotlin

沒有留言:

張貼留言