题目描述
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.
具体实现
class Solution {
public:
int rob(vector<int>& nums) {
if (nums.size() == 0) return 0;
vector< vector<int> > sum(nums.size(), vector<int>(2, 0));
sum[0][1] = nums[0];
int max = nums[0];
for (int i = 1; i < nums.size(); i++) {
sum[i][0] = sum[i-1][1] > sum[i-1][0] ? sum[i-1][1] : sum[i-1][0];
sum[i][1] = sum[i-1][0] + nums[i];
max = max > sum[i][0] ? max : sum[i][0];
max = max > sum[i][1] ? max : sum[i][1];
}
return max;
}
};
本文介绍了一个经典的计算机科学问题——房屋抢劫问题,并提供了一种有效的解决方案。该问题要求在一个街区中选择若干房屋进行抢劫,使得所获金额最大,但不能连续抢劫相邻的两栋房屋。文章通过动态规划的方法给出了具体的实现细节。
861

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



