标签:
题目:
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.
题目解答:
这个题目是在之前House Robber 和House Robber II之上的变体。它要求的是在树上的动归。需要用到深度优先搜索和动归的思想。一样的,相邻节点不能偷。
另外借助一个辅助结构,来帮助我们存动归中需要比较的两个值。
代码:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ struct robMoney //辅助数据结构,用来记录动态规划过程中的两个整型值 { int noRob; //不偷当前这一家,可以得到的金钱数目 int curRob; //在当前这个位置,可以获得到的金钱数目最大值 robMoney():noRob(0),curRob(0){} }; class Solution { public: int rob(TreeNode* root) { if(root == NULL) return 0; robMoney res = dfs(root); return res.curRob;//在当前位置所能获得的金钱数目最大值 } robMoney dfs(TreeNode *root) //深度优先搜索 { robMoney money; if(root == NULL) { return money; } robMoney left = dfs(root -> left); robMoney right = dfs(root -> right); money.noRob = left.curRob + right.curRob; //当前这家选择不偷 money.curRob = max(money.noRob, left.noRob + right.noRob + root -> val); //取二者的最大值 return money; } int max(int a, int b) { return a > b ? a : b; } };
标签:
原文地址:http://www.cnblogs.com/CodingGirl121/p/5548992.html