leetcode 198.213.337 House Robber

来源:互联网 发布:linux 启动 编辑:程序博客网 时间:2024/06/06 13:05

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.


House Robber 1:

给出一个数组,求出字数组的最大和,子数组中的成员不能使相邻的。

两个变量,一个保存当前计算下标前一个的最大和MAXV1,另一个是前两个的最大和MAXV2,则当前最大为max(MAXV1,(MAXV2+index_now))。

for循环上述式子,记住MAXV1,2的每个循环里面互换。


House Robber 2:

在1的基础上给出现在数组是一个环。

即增加了元数组首尾不能同时出现在子数组的条件。

解决方法很简单,将原数组分别剥离首、尾,进行两次House Robber 1,求出较大值。


*House Robber 3:

和前面有较大不同,将一维数组改成了二叉树,要求任何两个子节点之间不能相连,求最大值。

先分析简单情况,在一个节点的左右子树最大和已知的情况下,我们是否可以求得这个节点以下树的最大和?

答案是否定的,因为要求任何两个节点都不能相连,我们不能得知左右子树最大值是否包含着两个左右子节点,也就是无法判断我们在求父节点最大值的时候是否能包含进这个父节点的值。

进而想到,如果知道这左右子节点分别包含和不包含子节点的最大值,即with me left,without me left,with me right,without me right这四个值,我们就可以求出目前父节点的最大和:with me parent = root->val + without me left + without me right // without me parent = max(with me left,without me left) + max(with me right,without me right)。

递归。

问题来了,上述with me left,without me left,with me right,without me right这几个值如何返回?

可以考虑返回map,但是,更简单的则是引用形参,直接传回计算后的值。

最后递归的结束条件?root==NULL


1 , 2 , 3 的代码:

1:

class Solution {public:    int rob(vector<int>& nums){int length = nums.size();if (length == 0)return 0;if (length == 1)return nums[0];int maxV2 = nums[0];int maxV1 = max(nums[0], nums[1]);int temp = 0;for (int i = 2; i < length; ++i){temp = maxV1;maxV1 = max(maxV1, maxV2 + nums[i]);maxV2 = temp;}return max(maxV1,maxV2);}    int max(int a, int b){return a > b ? a : b;}};


2:

class Solution {public:    int rob(vector<int>& nums){int length = nums.size();if (length == 0)return 0;if (length == 1)return nums[0];int maxV2 = nums[0];int maxV1 = max(nums[0], nums[1]);int temp = 0;for (int i = 2; i < length-1; ++i){temp = maxV1;maxV1 = max(maxV1, maxV2 + nums[i]);maxV2 = temp;}int max1= max(maxV1,maxV2);if (length == 2)return max1;maxV2 = nums[1];maxV1 = max(nums[2], nums[1]);for (int i = 3; i < length; ++i){temp = maxV1;maxV1 = max(maxV1, maxV2 + nums[i]);maxV2 = temp;}int max2 = max(maxV1, maxV2);return max(max1, max2);}int max(int a, int b){return a > b ? a : b;}};


3:

class Solution {public: int bigger(int a, int b) { return a > b ? a : b; } void rob_max(TreeNode* root, int& wm, int& wom) { if (root == NULL) {     wm = wom = 0;     return; } wm = wom = 0;  int lwm = 0, lwom = 0; int rwm = 0, rwom = 0; rob_max(root->left, lwm, lwom); rob_max(root->right, rwm, rwom); wm = root->val + lwom + rwom; wom = bigger(lwm, lwom) + bigger(rwm, rwom); }int rob(TreeNode* root){int wm = 0, wom = 0;rob_max(root, wm, wom);return bigger(wm, wom);}};


0 0
原创粉丝点击