House Robber III

来源:互联网 发布:mac软件安装目录 编辑:程序博客网 时间:2024/05/28 15:12

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.

解法一:直接递归有很多duplication操作
考虑用dp,这里用一个数组保存已经知道的子树的rob()值

/** * 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:    map<TreeNode*,int> robmap;    int rob(TreeNode* root) {        if(root==NULL)return 0;            if(robmap.find(root)!=robmap.end())return robmap[root];            int ll=root->left?rob(root->left->left):0;            int lr=root->left?rob(root->left->right):0;            int rl=root->right?rob(root->right->left):0;            int rr=root->right?rob(root->right->right):0;            int res= max((root->val)+ll+lr+rl+rr,rob(root->left)+rob(root->right));            robmap[root]=res;            return res;    }    };

解法二:
考虑为什么会有那么多的duplication操作,因为计算rob(root)的时候要用到root下面两层子孙的值,因此考虑将root一层和root->son->son 一层进行decoupling,方法是让rob返回两个值,一个是包含自己的最大值一个是不包含自己的最大值,这样计算rob(root)的时候仅仅需要儿子一层的信息就可以

public int rob(TreeNode root) {    int[] res = robSub(root);    return Math.max(res[0], res[1]);}private int[] robSub(TreeNode root) {    if (root == null) {        return new int[2];    }    int[] left = robSub(root.left);    int[] right = robSub(root.right);    int[] res = new int[2];    res[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);    res[1] = root.val + left[0] + right[0];    return res;
0 0
原创粉丝点击