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.

Example 1:

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.

Example 2:

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.    

       一般来说,给定一个规则,让我们求任意状态下的解都是用动态规划。这里的规则是劫匪不能同时抢劫相邻的屋子,即我们在累加时,只有两种选择:一是如果选择了抢劫上一个屋子,那么就不能抢劫当前的屋子,所以最大收益就是抢劫上一个屋子的收益,二是如果选择抢劫当前屋子,就不能抢劫上一个屋子,所以最大收益是到上一个屋子的上一个屋子为止的最大收益,加上当前屋子里有的钱,所以,我们只要判断一下两个里面哪个大就行了,同时也是我们的递推式。当然我们也可以做一点优化,本来我们是要用一个dp数组来保存之前的结果的。但实际上我们只需要上次和上上次的结果,所以可以用两个变量就行了。

       优化前(空间复杂度为O(n)):

    public int rob(int[] nums) {
        int i;
        if(nums==null||nums.length==0)
            return 0;
        else if(nums.length<2)
            return nums[0];
        else if(nums.length==2)
            return Math.max(nums[0],nums[1]);
        int dp[] = new int[nums.length];
        dp[0] = nums[0];
        dp[1] = Math.max(nums[0], nums[1]);
        for(i=2;i<nums.length;i++){
        	dp[i] = Math.max(dp[i-2]+nums[i],dp[i-1]);
        }
        return dp[i-1];
    }
       优化后(空间复杂度为O(1)):
    public int rob(int[] nums) {
        if(nums.length <= 1){
            return nums.length == 0 ? 0 : nums[0];
        }
        int a = nums[0];
        int b = Math.max(nums[0], nums[1]);
        for(int i = 2; i < nums.length; i++){
            int tmp = b;
            b = Math.max(a + nums[i], b);
            a = tmp;
        }
        return b;
    }
       上面的代码其实就是最经典的动态规划算法的体现,是不是觉着挺简单的哈,当然只要我们用心去思考且内化了一个知识点,那么在解决相关问题上也就游刃有余了,这道题是比较简单的,但因为自己在算法方面一直都不是很擅长,所以已经体会到了这段时间的练习带给自己的帮助及提升。那么,戒骄戒躁、继续努力哈~
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值