LeetcodeHouse Robber

Posted wuezs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetcodeHouse Robber相关的知识,希望对你有一定的参考价值。

题目链接:https://leetcode.com/problems/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.

思路:

用n数组表示到当前元素为止的最大值。则n[i]只跟n[i-2]和n[i-1]有关,当n[i-1]大于n[i-2]+nums[i]的时候可以放弃抢劫nums[i],因为抢了还不如不抢,且抢了i-2、i-1的情况下都可以抢劫i+1。

算法:

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


以上是关于LeetcodeHouse Robber的主要内容,如果未能解决你的问题,请参考以下文章

LeetcodeHouse Robber

LeetCodeHouse Robber III(337)

198. House Robber

刷题198. House Robber

House Robber

CodeForces 686B Little Robber Girl's Zoo (构造冒泡排序)