首页 > 算法 > [LeetCode每日一题]198. House Robber
2020
03-12

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

Example:

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.

198. House Robber
你是一个强盗,要去沿着一条街盗窃,这条街上住户的钱用一个整数数组表示,为避免惊动警察,你不能偷盗连续两户人家,要求返回最大盗窃金额。
这道题可以用动态规划解决。设dp[i]表示到第i户时的最大金额。在第i户时你有两种选择:
1.偷,dp[i] = dp[i-2]+nums[i-1]
2.不偷 dp[i] = dp[i-1]
综上,状态转移方程为:

dp[i] = max(dp[i - 1], dp[i - 2] + nums[i - 1])

实现代码如下:

class Solution {
    public int rob(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        if (nums.length == 1) {
            return nums[0];
        }
        int len = nums.length;
        int[] dp = new int[len + 1];
        dp[1] = nums[0];
        for (int i = 2; i <= len; i++) {
            dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i - 1]);
        }
        return dp[len];
    }
}
最后编辑:
作者:lwg0452
这个作者貌似有点懒,什么都没有留下。
捐 赠如果您觉得这篇文章有用处,请支持作者!鼓励作者写出更好更多的文章!

留下一个回复

你的email不会被公开。