您的位置:首页 > 其它

每周LeetCode算法题(七): 题目: 198. House Robber

2017-10-19 12:42 453 查看

每周LeetCode算法题(七)

题目: 198. House Robber

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.

解法分析

题目的要求是,给定n间连续排列的房子,每间房子有一定数量的财物,作为一名小偷,要在不能同时选定相邻的两间房子下手的情况下,偷到最多数量的财物。

思路是,每次决定第i间房子该不该选择时,先考虑第i-2间房子和第i-1间房子。如果同时选择了第i间房子和第i-2间房子,那么第i-1间房子就不能选择。那么是否要选择第i间房子,取决于这样是否会得到更大的收益。若第i间房子+第i-2间房子的收益大于第i-1间房子,那么第i次的选择中最大的收益就是第i间房子+第i-2间房子的收益。否则,将不不选择第i间房子,而这次的选择的收益沿用上一次的收益,即选择第i-1间房子得到的收益。

当判断到最后,第n-1次的收益和第n-2次的收益中的最大者便是最终所求的最大收益。

C++代码

class Solution {
public:
int rob(vector<int>& nums) {
int a = 0;
int b = 0;
for (int i = 0; i < nums.size(); i++) {
int tmp = (a + nums[i] > b)? (a + nums[i]): b;
a = b;
b = tmp;
}
return (a > b)? a: b;
}
};


类似题目

213. House Robber II

After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.

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.

这题只是多了一个条件,第0间房子和第n-1间房子是相邻的,即这两间房子不能都选。于是问题分成了两部分,一个是第0到n-
4000
2间房子的选择,一个是第1到n-1间房子的选择。

class Solution {
public:
int rob(vector<int>& nums) {
int c1 = 0, c2 = 0;
int a = 0;
int b = 0;
if (nums.size() == 0) {
return 0;
} else if (nums.size() == 1) {
return nums[0];
}
for (int i = 0; i < nums.size() - 1; i++) {
int tmp = (a + nums[i] > b)? (a + nums[i]): b;
a = b;
b = tmp;
}
c1 = (a > b)? a: b;
a = 0;
b = 0;
for (int i = 1; i < nums.size(); i++) {
int tmp = (a + nums[i] > b)? (a + nums[i]): b;
a = b;
b = tmp;
}
c2 = (a > b)? a: b;
return (c1 > c2)? c1: c2;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: