[leetcode]337. House Robber III

来源:互联网 发布:scratch少儿趣味编程2 编辑:程序博客网 时间:2024/05/02 08:57

题目链接: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.


解题思路:动态规划,深度优先遍历二叉树。假设在root节点在L层,那么有两种情况。一:取root的值,root左节点和右节点不取;二:不取root节点,root的左节点和右节点可取可不取。通过记录每个节点取与不取得到的最大钱数,最后返回两个数中最大值。


class Solution{public:    int rob(TreeNode* root)    {        vector<int> res=dfs(root);        return max(res[0],res[1]);    }    vector<int> dfs(TreeNode* root)    {        vector<int> res(2,0);        if(root==NULL)        return res;        vector<int> left=dfs(root->left);        vector<int> right=dfs(root->right);        res[0]=left[1]+right[1]+root->val;        res[1]=max(left[0],left[1])+max(right[0],right[1]);        return res;    }};


0 0
原创粉丝点击