码迷,mamicode.com
首页 > 其他好文 > 详细

House Robber

时间:2015-06-25 12:19:18      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:

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:

 1  int rob(vector<int>& nums) {
 2         if (nums.empty())
 3             return 0;
 4         size_t length = nums.size();
 5         int result = 0;
 6         if (1==length)
 7             return nums[0];
 8         else if (2==length)
 9             return (nums[0]>=nums[1])?nums[0]:nums[1];
10         else
11         {
12             int p = nums[0], q=(nums[0]>=nums[1])?nums[0]:nums[1];
13             for (int i = 2; i <= length-1; ++i)
14             {
15                 int temp = p+nums[i];
16                 result=(temp>=q)?temp:q;
17                 p = q;
18                 q = result;
19             }
20         }
21         return result;
22     }

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

f(n)=max(f(n-1), f(n-2)+an)

House Robber

标签:

原文地址:http://www.cnblogs.com/happygirl-zjj/p/4599498.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!