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

198,House Robber

时间:2016-08-13 21:05:26      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:

一、题目


 

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.

二、分析


 

  一道简单的动态规划。

  f(k): 抢劫到第k个房间时得到的最大钱数

  则有以下的递推关系: 

f(0) = nums[0]
f(1) = max(num[0], num[1])
f(k) = max( f(k-2) + nums[k], f(k-1) )

三、代码


 

1)比较通俗易懂,诠释了上面三条公式

 1 class Solution {
 2 public:
 3     int rob(vector<int>& nums) {
 4         int length = nums.size();
 5         if (length == 0)
 6             return 0;
 7         vector<int> money(length, nums[0]);
 8         if (length == 1)
 9             return nums[0];
10         else {
11             money[1] = max(nums[0], nums[1]);
12             for (int i = 2; i < length; ++i) {
13                 money[i] = max(money[i-1], money[i-2] + nums[i]);
14             }
15         }
16         return money[length - 1];
17 
18     }
19 };

2)对上面程序的优化

 1 class Solution {
 2 public:
 3     int rob(vector<int>& nums) { 
 4         int n = nums.size(), pre = 0, cur = 0;
 5         for (int i = 0; i < n; i++) {
 6             int temp = max(pre + nums[i], cur);
 7             pre = cur;
 8             cur = temp;
 9         }
10         return cur;
11     }
12 };

 3)python实现

1 class Solution:
2     
3     def rob(self, nums):
4         
5         last, now = 0, 0
6         
7         for i in nums: last, now = now, max(last + i, now)
8                 
9         return now

 

 

198,House Robber

标签:

原文地址:http://www.cnblogs.com/letgo/p/5768817.html

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