[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 };

 

 

 

 

posted @ 2015-09-27 17:29  `Liok  阅读(232)  评论(0编辑  收藏  举报