您的位置:首页 > 其它

House Robber

2015-06-25 11:16 232 查看
Description:

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.

Code:

int rob(vector<int>& nums) {
if (nums.empty())
return 0;
size_t length = nums.size();
int result = 0;
if (1==length)
return nums[0];
else if (2==length)
return (nums[0]>=nums[1])?nums[0]:nums[1];
else
{
int p = nums[0], q=(nums[0]>=nums[1])?nums[0]:nums[1];
for (int i = 2; i <= length-1; ++i)
{
int temp = p+nums[i];
result=(temp>=q)?temp:q;
p = q;
q = result;
}
}
return result;
}


令f(n)表示从1号房子到n号房子可以偷到的最大钱数,则:

f(n)=max(f(n-1), f(n-2)+an)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: