您的位置:首页 > 其它

LeetCode 198. House Robber

2016-04-05 02:12 399 查看
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.

题目:你是一个非常牛逼的强盗,计划抢一条街。每个屋子里面都存有一定数量的钱,唯一制约你抢钱的原因是:相邻的屋子的安全系统是相连的,如果在同一个晚上,两个相邻的屋子被闯入了,安全系统会自动的报警。

求解你不惊动警察,能抢多少钱

这个题目是典型的动态规划,第i次决定是否抢钱,要看是前i-2个屋子里面能抢到的最多的钱与第i个屋子的钱之和是否大于前i-1个屋子里能抢到的最多的钱!

class Solution {
public:
//辅助函数,用来取出较大的数
int max(int a, int b)
{
return a > b ? a : b;
}
int rob(vector<int>& nums) {
//建立一个长度为n的向量,第i-1位用来保存前i家可以抢到的最多的钱
vector<int> money(nums.size(), 0);
if (0 == nums.size())return 0;
if (1 == nums.size())return nums[0];
else
{
money[0] = nums[0];
money[1] = max(nums[0], nums[1]);
for (unsigned int i = 2;i < nums.size();++i)
//得出前i家可以抢到的最多的钱
money[i] = max(nums[i] + money[i - 2], money[i - 1]);
}
return money[nums.size() - 1];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: