标签:oid ber solution sim treenode use led void class
每个节点是个房间,数值代表钱。小偷偷里面的钱,不能偷连续的房间,至少要隔一个。问最多能偷多少钱
TreeNode* cur
mp[{cur, true}]表示以cur为根的树,最多能偷的钱
mp[{cur, false}]表示以cur为根的树,不偷cur节点的钱,最多能偷的钱
可以看出有下面的关系
mp[{node, false}] = mp[{node->left,true}] + mp[{node->right,true}]
mp[{node, true}] = max(node->val + mp[{node->left,false}] + mp[{node->right,false}], mp[{node, false}])
class Solution { public: void helper(TreeNode* node, map<pair<TreeNode*, bool>,int>& mp){ if(!node){ return; } //a(node) //lk("root",node) helper(node->left, mp); helper(node->right, mp); mp[{node, false}] = mp[{node->left,true}] + mp[{node->right,true}]; mp[{node, true}] = max(node->val + mp[{node->left,false}] + mp[{node->right,false}], mp[{node, false}]); //dsp } int rob(TreeNode* root) { map<pair<TreeNode*, bool>,int> mp; //amap(mp, pair<TreeNode*, bool>,int) //ahd(root) mp[{NULL, true}]=0; mp[{NULL, false}]=0; helper(root, mp); return max(mp[{root, false}], mp[{root, true}]); } };
动态演示 http://simpledsp.com/FS/Html/lc337.html
LeetCode 337. House Robber III 动态演示
标签:oid ber solution sim treenode use led void class
原文地址:https://www.cnblogs.com/leetcoder/p/11356529.html