1. 程式人生 > >【LeetCode】337. House Robber |||

【LeetCode】337. House Robber |||

337. House Robber |||

Description:

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:

Input: [3,2,3,null,3,null,1]

     3
    / \
   2   3
    \   \ 
     3   1

Output: 7 
Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.

Example 2:

Input: 
[3,4,5,1,3,null,1]   3 / \ 4 5 / \ \ 1 3 1 Output: 9 Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.

解題思路:

(1)遞迴法:

關於樹的問題,首先想到的是用遞迴法求解。針對每一個樹節點我們給定一個長度為2的result列表。result[0]表示不搶劫當前節點能取到的最大值;result[1]表示搶劫當前節點能取到的最大值。

已經AC的程式碼:

# Definition for a binary tree node.
class TreeNode(object):
    """節點類"""
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Tree(object):

    # 建立二叉樹是以層序遍歷方式輸入,節點不存在時以 'None' 表示
    def creatTree(self, nodeList):
        if nodeList[0] == None:
            return None
        head = TreeNode(nodeList[0])
        Nodes = [head]
        j = 1
        for node in Nodes:
            if node != None:
                node.left = (TreeNode(nodeList[j]) if nodeList[j] != None else None)
                Nodes.append(node.left)
                j += 1
                if j == len(nodeList):
                    return head
                node.right = (TreeNode(nodeList[j]) if nodeList[j] != None else None)
                j += 1
                Nodes.append(node.right)
                if j == len(nodeList):
                    return head

class Solution:

    def rob(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        return max(self.tryRob(root))

    def tryRob(self, node):
        if node == None:
            return [0, 0]
        # result[0] is max value if not rob current node
        # result[1] is max value if rob current node
        result = [0] * 2
        left_val = self.tryRob(node.left)
        right_val = self.tryRob(node.right)
        result[0] = max(left_val[0], left_val[1]) + max(right_val[0], right_val[1])
        result[1] = left_val[0] + right_val[0] + node.val
        return result

if __name__ == "__main__":
    elements = [3, 4, 5, 1, 3, None, 1]
    tree = Tree()
    head = tree.creatTree(elements)
    solution = Solution()
    print("result:{}".format(solution.rob(head)))

Reference:

【1】Python --- 二叉樹的層序建立與三種遍歷https://www.cnblogs.com/tomhawk/p/7464639.html

【2】House Robber |/||/|||:http://v.youku.com/v_show/id_XMjg3ODQwMjk0MA==.html?spm=a2h0j.11185381.listitem_page1.5~A