LeetCode 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.
class Solution {
#define max(a,b) (a>b?a:b)
public:
int rob(vector<int>& nums) {
int sum1 = 0, sum2 = 0;
int count = nums.size();
if (0 == count)
{
return 0;
}
for (int i = 0; i < count; i++)
{
if (i % 2 == 0)
sum1 = max(sum1 + nums[i], sum2);
else
sum2 = max(sum2 + nums[i], sum1);
}
return max(sum1, sum2);
}
};
本文介绍LeetCode上的一道经典动态规划问题——打家劫舍(House Robber)。该问题要求从一系列房屋中挑选一些进行抢劫,但不能连续抢劫相邻的两座房屋。文章详细解释了如何通过动态规划算法找到最优解,并给出了一段C++代码实现。
4579

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



