LeetCode No.337 House Robber III

来源:互联网 发布:json格式用什么打开 编辑:程序博客网 时间:2024/05/24 06:35

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.

====================================================================================================================================

这道题目跟leetcode198题的意思差不多,只是多了一个条件。其大意是:一个小偷要去一条(二叉树形)街道偷东西,每间房子都有一定数量的金钱,但小偷不能偷任意相连的两间房子的金钱,不然就会触发警报系统。求小偷在不触发警报系统情况下能偷到的最大金额。

对于每一个节点,我们都有两种处理方式,即偷与不偷。用ans[0]表示不偷该节点,ans[1]表示偷该节点,则有

ans[0] = max ( left[0] , left[1] ) + max ( right[0] , right[1] ) ;// ans[0] doesn't contains the rootans[1] = root -> val + left[0] + right[0] ;                       // ans[1] contains the root

附上代码:

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int rob(TreeNode* root) {        vector <int> ans = BinarySearch ( root ) ;        return max ( ans[0] , ans[1] ) ;    }    vector <int> BinarySearch ( TreeNode* root )    {        if ( root == NULL )            return vector <int> ( 2 , 0 ) ;        vector <int> left = BinarySearch ( root -> left ) ;        vector <int> right = BinarySearch ( root -> right ) ;        vector <int> ans ( 2 , 0 ) ;        ans[0] = max ( left[0] , left[1] ) + max ( right[0] , right[1] ) ;// ans[0] doesn't contains the root        ans[1] = root -> val + left[0] + right[0] ;                       // ans[1] contains the root        return ans ;    }};




0 0