admin管理员组

文章数量:1558103

题目:

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.

链接:https://leetcode/problems/house-robber/

法一:状态压缩

这道理可以看做是状态压缩,每两个数字看做是一行,状态有3个,故需要F[N][3]的数组,F[i][j]就表示第i行状态j时rob的money。

具体状态压缩可以看我这两篇blog: 算法练习系列—hiho1048 状态压缩一(铺地砖)  算法练习系列—hiho1044 状态压缩二(捡垃圾)

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

#define N 10000

class Solution {
public:
	Solution(){
		memset(F, 0, sizeof(int)*N*3);
	}
    int rob(vector<int> &num) {
		if(num.size() == 0) return 0;
		else if(num.size() == 1) return num[0];
		else{
			// 初始化第一行
			F[0][0] = 0;
			F[0][1] = num[1];
			F[0][2] = num[0];
			int maxMoney = max(num[1], num[0]);
			for(int i = 1; i < num.size()-1; i++){
				for(int j = 0; j < 3; j++){     
					int t = j >> 1;
					for(int k = 0; k < 3; k++){
						if( t ==  (k & (1>>0))){      // 判断第i行状态j与第i-1行各个状态是否兼容 即j的倒数第二位与k的倒数第一位是否相同
							F[i][j] = max(F[i-1][k], F[i][j]);	//  输出兼容的最大者
						}
					}
					if((j & (1<<0)) == 1) F[i][j] = F[i][j] + num[i+1];  // 如果状态j最后一位为1则 需要加上该方案数
					if(F[i][j] > maxMoney){                // 求最大的方案数
						maxMoney = F[i][j];
					}
				}
			}
			return maxMoney;
		}
    }
private:
	int F[N][3];
};

法二:动态规划

这题可以看做是简单的DP问题,用A[0]表示没有rob当前house的最大money,A[1]表示rob了当前house的最大money,那么A[0] 等于rob或者没有rob上一次house的最大值

即A[i+1][0] = max(A[i][0], A[i][1])..  那么rob当前的house,只能等于上次没有rob的+money[i+1], 则A[i+1][1] = A[i][0]+money[i+1].

实际上只需要两个变量保存结果就可以了,不需要用二维数组

class Solution {
public:
    int rob(vector<int> &num) {
        int best0 = 0;   // 表示没有选择当前houses
        int best1 = 0;   // 表示选择了当前houses
        for(int i = 0; i < num.size(); i++){
            int temp = best0;
            best0 = max(best0, best1); // 没有选择当前houses,那么它等于上次选择了或没选择的最大值
            best1 = temp + num[i]; // 选择了当前houses,值只能等于上次没选择的+当前houses的money
        }
        return max(best0, best1);
    }
};


本文标签: HouseRobber