198,House Robber

时间:2022-07-26 14:31:32

一、题目


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() = nums[]
f() = max(num[], num[])
f(k) = max( f(k-) + nums[k], f(k-) )

三、代码


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

 class Solution {
public:
int rob(vector<int>& nums) {
int length = nums.size();
if (length == )
return ;
vector<int> money(length, nums[]);
if (length == )
return nums[];
else {
money[] = max(nums[], nums[]);
for (int i = ; i < length; ++i) {
money[i] = max(money[i-], money[i-] + nums[i]);
}
}
return money[length - ]; }
};

2)对上面程序的优化

 class Solution {
public:
int rob(vector<int>& nums) {
int n = nums.size(), pre = , cur = ;
for (int i = ; i < n; i++) {
int temp = max(pre + nums[i], cur);
pre = cur;
cur = temp;
}
return cur;
}
};

3)python实现

 class Solution:

     def rob(self, nums):

         last, now = 0, 0

         for i in nums: last, now = now, max(last + i, now)

         return now