[leetcode-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.

思路:

对于中间某个房间i,有两种状态,要么偷,要么不偷。

偷得话总的钱就是money[i-2]+nums[i],如果不偷,总的钱就是money[i-1]

于是 money[i] = max{money[i-2]+nums[i],money[i-1]}

很容易写出如下代码:

时间复杂度为O(n),空间复杂度为O(n)。

int rob(vector<int>& nums) 
    {//money[i] = max{money[i-2]+nums[i],money[i-1]}第i个房间有两种可能
        //要么偷,要不不偷,偷的话就是money[i-2]+nums[i] 不偷就是,money[i-1]
        if (nums.empty())return 0;
        if (nums.size() == 1) return nums[0];
        if (nums.size() == 2) return max(nums[0],nums[1]);
        vector<int>money(nums.size());
        money[0] = nums[0];
        money[1] = max(nums[0], nums[1]);
        for (int i = 2; i < nums.size();i++)
        {
            money[i] = max(money[i-2]+nums[i],money[i-1]);
        }
        return money.back();        
    }

其实还有时间复杂度为O(1)的方法。。(⊙o⊙)…目前还没有看懂:

For every house k, there are two options: either to rob it (include this house: i) or not rob it (exclude this house: e).

  1. Include this house:
    i = num[k] + e (money of this house + money robbed excluding the previous house)

  2. Exclude this house:
    e = max(i, e) (max of money robbed including the previous house or money robbed excluding the previous house)
    (note that i and e of the previous step, that's why we use tmp here to store the previous i when calculating e, to make O(1) space)

Here is the code:

public class Solution {
    public int rob(int[] num) {
        int i = 0;
        int e = 0;
        for (int k = 0; k<num.length; k++) {
            int tmp = i;
            i = num[k] + e;
            e = Math.max(tmp, e);
        }
        return Math.max(i,e);
    }
}

 

参考:

https://discuss.leetcode.com/topic/11354/dp-o-n-time-o-1-space-with-easy-to-understand-explanation

http://qiaopeng688.blog.51cto.com/3572484/1844956

 

转载于:https://www.cnblogs.com/hellowooorld/p/6501413.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值