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

[LeetCode每日一题]213. House Robber II

题目如下:

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, 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: [2,3,2]
Output: 3
Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2),
             because they are adjacent houses.

213. House Robber II
你是一个强盗,要去沿着一条街盗窃,这条街上住户的钱用一个整数数组表示,为避免惊动警察,你不能偷盗连续两户人家(第一户和最后一户是相邻的),要求返回最大盗窃金额。
这道题可以用动态规划解决。当第一户和最后一户不相邻时,解决方法请参考 [LeetCode每日一题]198. House Robber。对于第一户和最后一户相邻的情况,可以将状态空间增加一个维度,设dp[i][0]表示到第i户时没偷第一户的最大金额,dp[i][1]表示到第i户时偷了第一户的最大金额。在第i户时你有两种选择:
综上,状态转移方程为(i != nums.length):

dp[i][0] = Math.max(dp[i - 1][0], dp[i - 2][0] + nums[i - 1]);
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 2][1] + nums[i - 1]);

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

留下一个回复

你的email不会被公开。