题目描述
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.
计算小偷一晚上偷钱的最大数额,不能连续偷相邻两家,用数组nums代表每一家的现金数。
解题思路
令re[i]表示偷到 i 时的最大数额,re[n]即为所求。小偷在 i 时有两个选择:
1、偷,说明前一家没偷,此时最大数额为re[i-2]+ nums[i]
2、不偷,说明偷了前一家,此时数额为 re[i-1]
因此 re[i] = max(re[i-1],re[i-2]+ nums[i])
代码如下
class Solution {
public:
int rob(vector<int>& nums) {
if (nums.size() >= 3) {
vector<int> re(nums.size(), 0);
re[0] = nums[0];
re[1] = re[1] = fmax(re[0], 0 + nums[1]);
for (int i = 2; i < nums.size(); i++) {
re[i] = fmax(re[i - 2] + nums[i], re[i - 1]);
}
return re[nums.size() - 1];
}
else if (nums.size() == 2) {
return (nums[0] > nums[1]) ? nums[0] : nums[1];
}
else if (nums.size() == 1)
return nums[0];
else
return 0;
}
};注意考虑nums大小,以及re[0]、re[1]的初始化:
可以考虑re[-2]、re[-1]都为0,从而得出re[0],re[1]
本文介绍了一种解决“打家劫舍”问题的方法,该问题要求计算在一排房子里,不抢劫相邻房屋的情况下,所能获得的最大金额。通过动态规划的方式,递推计算每个房屋在被抢或不被抢时的最大收益。
1624

被折叠的 条评论
为什么被折叠?



