198 House 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.

解题思路:
这题的考点是动态规划
动态规划一定要找递推公式!!!
1. 对这题来说,对每一家房子,在其前一家房子偷不偷的前提下,有两种可能的情况。
2. 前一家房子被偷了,它就不能再偷了。前一家房子没被偷,它可以被偷也可以选择不偷。
3. 可看出,每一个子问题都依赖于前一个子问题,同时每一个子问题都会产生至少一种情况(之多两种情况)。
4. 根据上述分析,得到递推公式:
money[i][0] = max(money[i - 1][0], money[i - 1][1])
上述公式表示,不偷第 i 家房子,当前最大收益就是前一家房子的最大收益,前一家房子可能被偷了,也可能没有被偷。
money[i][1] = money[i - 1][0] + nums[i]
上述公式表示,要偷第 i 家的房子,必须在不偷第 i-1 家房子的前提下,才能加上偷第 i 家获得的收益。

代码实现:

public class Solution {
    public int rob(int[] nums) {
        if(nums == null || nums.length == 0)
            return 0;
        int[] money = new int[2];
        money[0] = 0;
        money[1] = nums[0];
        for(int i = 1; i < nums.length; i ++) {
            int temp = money[0];
            money[0] = Math.max(money[0], money[1]);
            money[1] = temp + nums[i];
        }
        return money[0] > money[1] ? money[0] : money[1];
    }
}
69 / 69 test cases passed.
Status: Accepted
Runtime: 0 ms
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值