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.ide
Determine the maximum amount of money the thief can rob tonight without alerting the police.post
Example 1:this
3 / \ 2 3 \ \ 3 1
Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.spa
給定一二叉樹,樹節點上有權值,從樹中選取一些不直接相鄰的節點,使得節點和最大code
1. 簡單粗暴,搜索完事,一個節點不外乎兩種狀況,選擇 or 不選擇;另外當前節點選擇以後,子節點不能被選擇;當前節點若不選擇,則又能夠分爲四種狀況orm
* 左選擇,右不選blog
* 右選,左不選it
* 左右都選io
* 左右都不選event
2. 寫代碼,好的然而超時(固然-_-後來看了其餘的解答,才發現too young)
3. 由於看到有重複計算,因而朝動態規劃考慮,因而想出這麼個狀態
d[0][1],其中0表示存儲遍歷到當前節點時,取當前節點能達到的最大值,而1則表示,不取當前節點能達到的最大值
又由於是樹節點,因此直接哈希表存儲d[TreeNode*][]
4. 遍歷順序呢,習慣性後序遍歷
5. 計算規則
// 顯然,當前節點取了,子節點不能取
d[TreeNode*][0] = TreeNodeVal + d[LeftChild][1] + d[RightChild][1]
// 四種狀況
d[TreeNode*][1] = max(d[LeftChild][0] + d[RightChild][0], d[LeftChild][1] + d[RightChild][0], d[LeftChild][0] + d[RightChild][1], d[LeftChild][1] + d[RightChild][1])
6. 總算過了,附代碼;看了討論的思路以後,以爲真是too young,╮(╯▽╰)╭
1 class Solution { 2 public: 3 int rob(TreeNode* root) { 4 if (root == NULL) { 5 return 0; 6 } 7 8 postOrder(root); 9 return max(d[root][0], d[root][1]); 10 } 11 12 void postOrder(TreeNode* itr) { 13 if (itr == NULL) { 14 return; 15 } 16 17 postOrder(itr->left); 18 postOrder(itr->right); 19 20 auto dItr = d.insert(pair<TreeNode*, vector<int>>(itr, vector<int>(2, 0))); 21 auto leftItr = dItr.first->first->left; 22 auto rightItr = dItr.first->first->right; 23 24 int rL = dItr.first->first->left != NULL ? d[dItr.first->first->left][0] : 0; 25 int rR = dItr.first->first->right != NULL ? d[dItr.first->first->right][0] : 0; 26 int uL = dItr.first->first->left != NULL ? d[dItr.first->first->left][1] : 0; 27 int uR = dItr.first->first->right != NULL ? d[dItr.first->first->right][1] : 0; 28 29 dItr.first->second[0] = dItr.first->first->val + uL + uR; 30 dItr.first->second[1] = max(max(max(rL + uR, uL + rR), rL + rR), uL + uR); 31 } 32 33 private: 34 unordered_map<TreeNode*, vector<int>> d; 35 };