您的位置:首页 > 编程语言 > Go语言

LeetCode Algorithms #198 <House Robber>

2016-03-24 15:28 477 查看
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.

思路:

和另一道简单题走楼梯,一步、两步那个类似。都是动态规划的问题,一个住户能不能被偷,取决于他前一个能不能被偷,所以到这个住户能偷到的最多钱是 (1.偷这家,以及这家前面相隔一家那里为止,偷的最多的钱的和。2.不偷这家,这家前面相邻那一家为止,前面偷最多钱。 )1,2中多的那一个。

编程实现这个就可以。

解:

class Solution {
public:
int rob(vector<int>& nums) {
if (nums.size() <= 1) return nums.empty() ? 0 : nums[0];
int maxEven = nums[0];
int maxOdd = max(nums[1],nums[0]);

for(int idx = 2; idx < nums.size(); idx++)
{
if(!(idx % 2))
maxEven = max(maxEven + nums[idx], maxOdd);
else
maxOdd = max(maxOdd + nums[idx], maxEven);
}

return max(maxEven,maxOdd);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: