LeetCode 198. House Robber

来源:互联网 发布:谁是最可爱的人 知乎 编辑:程序博客网 时间:2024/05/22 05:18

198. 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.子问题划分
      设m[i] i=1...len 是保存 抢劫前i个房间所获得的最大金钱数量。由题意我可知,若想保证抢劫前len个房间所获金额最大,则抢劫前i个房间时
    所获金额一定也是当前1..i段中最大的。
   
    2.递推方程
       初值: m[0]=nums[0],
                m[1]=max{m[0],nums[1]}   即抢劫前两个房间所获的金钱 只取其中较大者
       方程:   m[i]=Max{m[i-2]+nums[i],m[i-1]}  ,  len>i>1
m[i-2]+nums[i]即代表抢劫第i个房间,不抢第i-1个反击,此时的获得的金钱数是就是抢劫前i-2个房间的金钱数假设第i个房间的金钱
m[i-1]即代表不抢第i个房间,此时的m[i]等于之前计算出的抢劫前i-1个房间所得金额
        

      3.输出
最后输出即决定是不是要抢最后一个房间,若抢则输出m[len-1],若不抢则输出m[len-2]  (抢不抢由其大小决定)



代码:

   public int rob(int[] nums) {    int len = nums.length;    if(len == 0)    return 0;    if(len == 1)    return nums[0];    int m[] = new int[len];    m[0] = nums[0];    m[1] = Math.max(nums[1],m[0]);    for(int i=2;i<len;i++){    m[i] = Math.max(m[i-2]+nums[i],m[i-1]);    }    return Math.max(m[len-2], m[len-1]);    }



原创粉丝点击