zoukankan      html  css  js  c++  java
  • 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.

    此题和House Robber的不同在于,这个是首尾相连的,需要多考虑一步,当没选中第一个房子的时候可以选择最后一个房子,而当选中第一个房子的时候不可以选择最后一个房子。做法是把数组分成两个部分,然后求这两个部分最大值进行比较,代码如下:

    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]);

            if(nums.length==3) return Math.max(nums[0],Math.max(nums[1],nums[2]));

            return Math.max(helper(Arrays.copyOfRange(nums,0,nums.length-1)),helper(Arrays.copyOfRange(nums,1,nums.length)));

        }

        public int helper(int[] nums){

            int[] dp = new int[nums.length];

            dp[0] = nums[0];

            dp[1] = Math.max(nums[0],nums[1]);

            for(int i=2;i<nums.length;i++){

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

            }

            return dp[nums.length-1];

        }

    }

    这个代码初始值要多判断很多步,下面来一个简练的:

    public class Solution {

        public int rob(int[] nums) {

            if(nums.length==0) return 0;

            if(nums.length==1) return nums[0];

            return Math.max(helper(nums,0,nums.length-2),helper(nums,1,nums.length-1));

        }

        public int helper(int[] nums,int start,int end){

            int include = 0;

            int exclude = 0;

            for(int j=start;j<=end;j++){

                int i=include,e=exclude;

                include = e+nums[j];

                exclude = Math.max(i,e);

            }

            return Math.max(include,exclude);

        }

    }

  • 相关阅读:
    Js获取时间,当前,一周前,一月前的时间,时间戳转换,时间格式化,日期格式化
    echarts图随窗口大小的变化而变化
    Vue中使用Google地图插件
    element el-progress渐变色进度条
    Vue中使用mixins
    CSS3 使用 calc() 计算高度 vh px
    element-ui饿了么框架中导航菜单中箭头方向问题
    Vue中使用QRcode.js生成二维码---qrcodejs2
    鼠标经过时显示样式的两种方法
    element 按钮样式:确认按钮发布后样式发生改变
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6357869.html
Copyright © 2011-2022 走看看