LeetCode | 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.

分析与思路

题目的意思是要求出 数组里所有不相邻的数据进行组合 所得到的最大值。

原则:相邻数不能被同时被rob。也即当i被rob时,i+1不能被rob。

方法一


我们开一个数组a[],元素a[i]表示当i被rob时所能得到的最大值。那么在每4个相邻的元素 i, i+1, i+2, i+3里,
一定有: a[i+2] >= a[i] 和a[i+3] >= a[i]

假如当前为第i个house,当前被rob后的值是 第i-2 rob  或者  第i-2 没有被rob 时的值与当前值的和,而i-2没有被rob时最大的值是a[i-3]的值
a[i] = max(a[i-2]+a[i], a[i-3]+a[i])

具体方法为:

假设数据: 6 4 2 8 3 6 2

那么首先可能选取 6 或者 4

每一个数字的选取都是根据他的前两个数字,前三个数字得到的最大值进行选择,等到2的时候考虑前面,只能和6组合 :6 4 8

到数字8,那么就可以考虑在6,4中进行组合 6 4 8 14

接下来的步骤:

6 4 8 14 11 
6 4 8 14 11 20 
6 4 8 14 11 20 16

最终是20.

代码:

int rob(vector<int>& nums)
{
	if(nums.empty())	return 0;
	int length = nums.size();
	if(length == 1)	return nums[0];
	if(length >= 3)
		nums[2] += nums[0];
	for(int i=3;i<length;i++)
	{
		if(nums[i-3]>nums[i-2])
			nums[i]+=nums[i-3];
		else 
			nums[i]+=nums[i-2];
	}
	return nums[length-1]>nums[length-2]?nums[length-1]:nums[length-2];
}

方法二

这个方法引自 小村庄的博客

这题可以看做是简单的动态规划问题,用A[0]表示没有rob当前house的最大money,A[1]表示rob了当前house的最大money,
A[0] = 
那么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].
实际上只需要两个变量保存结果就可以了,不需要用二维数组

代码:

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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值