题目:
你是一个计划沿街抢劫房屋的职业强盗。每个房子都有一定数量的钱被藏起来,阻止你抢劫他们的唯一限制是相邻的房子都有安全系统连接,如果两个相邻的房子在同一天晚上被闯入,它会自动联系警察。给出一个非负整数列表,表示每户人家的钱数,确定你今晚不报警就能抢劫的最大钱数。
也就是说:给定一个非负整数列表,在不能取相邻两个数的情况下,求所取的所有数的最大和
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.
Input: [1,2,3,1] Output: 4 Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. Input: [2,7,9,3,1] Output: 12 Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12.
思路:
以数组[2,7,9,3,1,10,8,5,6]为例
(自上而下的思路)
在不取相邻的两个数的情况下,求所取的所有数的最大和,可知,最后一定会取5或者6——如果不取6,则是以5结尾,因为如果不以5结尾,那么5,6都是没有被取到的非负数,任意加上一个数都会比原来的和更大,所以与题设矛盾,可得5或6一定会被取到
这样,问题就转变为了max([……5],[……8,6]),第一个数组是从第一个数开始到5为止,第二个数组是从第一个数开始到8为止再加上6(因为相邻不可取,所以5被排除掉)
对于这两个数组,又可转化为更小数组的计算
(自下而上的思路)
依旧以[2,7,9,3,1,10,8,5,6]为例,用一个int[nums.length] re来存储以每个位置为结尾的最大和
可知:
re[0] = nums[0] = 2
re[1] = max(nums[0],nums[1]) = 7
在9的位置,可以有两种选择,一种是2+9,一种是7,也就是上面思路所提到的,选择最后一位数与否的两种结果
re[2] = max(nums[2]+nums[0] , nums[1])
在3的位置,也可以有两种选择,一种是3+7,一种是9+2
re[3] = max(nums[3]+nums[1], nums[2]+nums[0])
re[4] = max(nums[4]+nums[2]+nums[0], nums[3]+nums[1])
可见,每个位置都是对两种选择的求最大值
re[4] 也等同于max(nums[4] + nums[0~2]的最大值=nums[4] + re[2],nums[0~3]的最大值=re[3])
所以可以得出这个式子re[ i ] = max( nums[ i ] + re[ i-2 ] , re[ i-1 ] )
【代码】
class Solutio{
public int rob(int[] nums) {
if(nums.length==0) {
return 0;
}
if(nums.length==1) {
return nums[0];
}
// 初始化
int[] re = new int[nums.length];
re[0] = nums[0];
re[1] = max(nums[0], nums[1]);
for(int i=2;i<nums.length;i++) {
re[i] = max(nums[i]+re[i-2], re[i-1]);
}
return re[nums.length-1];
}
// 最大值
public int max(int a,int b) {
return a>b?a:b;
}
}