【Leetcode】213. House Robber II 【动态规划】

213. House Robber II


Note: This is an extension of House Robber.

After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.

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.


思路:

与198题的区别在于,213首尾相接,198是简单的数组,即,首尾不能同时出现。

解决方案,调用两次动态规划算法,分别去除首跟尾结点,计算结果,比较两个值,返回较大的。

动态规划算法:

当前抢到钱robSum[i] 为 robSum[i-2] + nums[i] 和 robSum[i-1]之中的较大值。


需要注意:

1、robSum 的初始值赋值。需要两个值。

2、以及把坐标当做参数传入函数时,变量 i 的起始终止条件的赋值。(因为参数nums的下标和robSum的下标不同,易出错)


import java.lang.Math.*;
public class Solution {
    public int rob(int[] nums) {
        if(nums.length == 0) return 0;
        if(nums.length == 1) return nums[0];
        if(nums.length == 2) return Math.max(nums[0],nums[1]);
        
        return Math.max(subrob(1,nums.length-1,nums),subrob(0,nums.length - 2,nums));
        
    }
    
    public int subrob(int begin , int end , int[] nums){
        int length = end - begin + 1; 
        int[] robSum = new int[length];
        robSum[0] = nums[begin];
        robSum[1] = Math.max(nums[begin],nums[begin + 1]);
        for(int i = 2 ; i < length ; i ++){
            robSum[i] = Math.max(robSum[i - 2] + nums[begin + i] , robSum[i-1]); 
        }
        return robSum[end - begin];
    }
}

Runtime: 1 ms

你可能感兴趣的:(leetcode,java,leetcode)