# leetcode198-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.

1. #include <iostream>
2. #include <algorithm>
3. #include <vector>
4. using namespace std;
5.
6. #define N 10000
7.
8. class Solution {
9. public:
10.     Solution(){
11.         memset(F, 0, sizeof(int)*N*3);
12.     }
13.     int rob(vector<int> &num) {
14.         if(num.size() == 0) return 0;
15.         else if(num.size() == 1) return num[0];
16.         else{
17.             // 初始化第一行
18.             F[0][0] = 0;
19.             F[0][1] = num[1];
20.             F[0][2] = num[0];
21.             int maxMoney = max(num[1], num[0]);
22.             for(int i = 1; i < num.size()-1; i++){
23.                 for(int j = 0; j < 3; j++){
24.                     int t = j >> 1;
25.                     for(int k = 0; k < 3; k++){
26.                         if( t ==  (k & (1>>0))){      // 判断第i行状态j与第i-1行各个状态是否兼容 即j的倒数第二位与k的倒数第一位是否相同
27.                             F[i][j] = max(F[i-1][k], F[i][j]);  //  输出兼容的最大者
28.                         }
29.                     }
30.                     if((j & (1<<0)) == 1) F[i][j] = F[i][j] + num[i+1];  // 如果状态j最后一位为1则 需要加上该方案数
31.                     if(F[i][j] > maxMoney){                // 求最大的方案数
32.                         maxMoney = F[i][j];
33.                     }
34.                 }
35.             }
36.             return maxMoney;
37.         }
38.     }
39. private:
40.     int F[N][3];
41. };

1. class Solution {
2. public:
3.     int rob(vector<int> &num) {
4.         int best0 = 0;   // 表示没有选择当前houses
5.         int best1 = 0;   // 表示选择了当前houses
6.         for(int i = 0; i < num.size(); i++){
7.             int temp = best0;
8.             best0 = max(best0, best1); // 没有选择当前houses，那么它等于上次选择了或没选择的最大值
9.             best1 = temp + num[i]; // 选择了当前houses，值只能等于上次没选择的+当前houses的money
10.         }
11.         return max(best0, best1);
12.     }
13. };
• 本文已收录于以下专栏：

举报原因： 您举报文章：leetcode198-House Robber 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)