zoukankan      html  css  js  c++  java
  • [LeetCode][JavaScript]House Robber II

    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.

    https://leetcode.com/problems/house-robber-ii/


    和House Robber新相比,房子首尾相连。

    动态规划和上一题一样的思路:http://www.cnblogs.com/Liok3187/p/4842444.html

    分成2次,第一次从第一间房子开始到倒数第二间结束;

    第二次从第二间开始到最后一间结束。

    粗暴地写两遍:

     1 /**
     2  * @param {number[]} nums
     3  * @return {number}
     4  */
     5 var rob = function(nums) {
     6     if(nums.length === 0){
     7         return 0;
     8     }else if(nums.length === 1){
     9         return nums[0];
    10     }
    11     var dp = [];
    12     dp[0] = 0;
    13     dp[1] = nums[0];
    14     for(var i = 2; i <= nums.length - 1; i++){
    15         dp[i] = Math.max(dp[i - 2] + nums[i - 1], dp[i - 1]);
    16     }
    17     var candidate = dp[nums.length - 1];
    18 
    19     dp = [];
    20     dp[1] = 0;
    21     dp[2] = nums[1];
    22     for(var i = 3; i <= nums.length; i++){
    23         dp[i] = Math.max(dp[i - 2] + nums[i - 1], dp[i - 1]);
    24     }
    25 
    26     return Math.max(candidate, dp[nums.length]);
    27 };

    封装成方法:

     1 /**
     2  * @param {number[]} nums
     3  * @return {number}
     4  */
     5 var rob = function(nums) {
     6     if(nums.length === 0){
     7         return 0;
     8     }else if(nums.length === 1){
     9         return nums[0];
    10     }
    11     return Math.max(robbing(1, nums.length - 1), robbing(2, nums.length));
    12 
    13     function robbing(start, end){
    14         var dp = [];
    15         dp[start - 1] = 0;
    16         dp[start] = nums[start - 1];
    17         for(var i = start + 1; i <= end; i++){
    18             dp[i] = Math.max(dp[i - 2] + nums[i - 1], dp[i - 1]);
    19         }
    20         return dp[end];
    21     }   
    22 };
  • 相关阅读:
    Git 分支开发规范
    小程序技术调研
    弹性布局
    vue 自定义指令的魅力
    记一次基于 mpvue 的小程序开发及上线实战
    mpvue学习笔记-之微信小程序数据请求封装
    微信小程序开发框架 Wepy 的使用
    Hbuilder 开发微信小程序的代码高亮
    luogu3807 【模板】 卢卡斯定理
    luogu1955 [NOI2015] 程序自动分析
  • 原文地址:https://www.cnblogs.com/Liok3187/p/4842453.html
Copyright © 2011-2022 走看看