[LeetCode]House Robber

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.

Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.

DP,写出递推公式很重要。

vector<int> f(n,0)表示抢第n家的最大收益;

vector<int> g(n,0)表示不抢第n家的最大收益。

那么有:

f[i] = g[i-1]+nums[i];
g[i] = max(f[i-1],g[i-1])。

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

迭代可以在O(1)的空间实现。

 1 class Solution {
 2 public:
 3     int rob(vector<int>& nums) {
 4         int n = nums.size();
 5         if(n<1) return 0;
 6         int f = nums[0];
 7         int g = 0;
 8         for(int i=1;i<n;i++)
 9         {
10             int tmp = f;
11             f = g+nums[i];
12             g = max(tmp,g);
13         }
14         return max(f,g);
15     }
16 };
原文地址:https://www.cnblogs.com/Sean-le/p/4814883.html