标签:
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.
思路:
动态规划
我的代码1:
public class Solution { public int rob(int[] nums) { if(nums == null || nums.length == 0) return 0; int len = nums.length; if(len == 1) return nums[0]; if(len == 2) return Math.max(nums[0],nums[1]); int max = Integer.MIN_VALUE; for(int i=0; i<len; i++) { if(len == 3) max = Math.max(max,nums[i]); else if(len == 4) max = Math.max(max, nums[i]+nums[(i+2)%len]); else if(len == 5) max = Math.max(max, nums[i]+Math.max(nums[(i+2)%len], nums[(i+3)%len])); else { int[] result = new int[len-3]; int k = 0; result[k++] = nums[(i+2)%len]; result[k++] = Math.max(nums[(i+2)%len],nums[(i+3)%len]); for(int j = (i+4)%len; j != (i-1+len)%len; j = (j+1)%len,k++) { result[k] = Math.max(result[k-1],nums[j]+result[k-2]); } max = Math.max(max, result[len-4]+nums[i]); } } return max==Integer.MIN_VALUE?0:max; } }
我的代码2:
public class Solution { public int rob(int[] nums) { if(nums == null || nums.length == 0) return 0; int len = nums.length; if(len == 1) return nums[0]; if(len == 2) return Math.max(nums[0],nums[1]); return Math.max(rob(nums, 1, 0), rob(nums, 2, 1)); } public int rob(int[] nums, int l, int h) { int len = nums.length; int[] result = new int[len-1]; int k = 0; result[k++] = nums[l]; result[k++] = Math.max(nums[(l+1)%len],nums[l]); for(int j=(l+2)%len; j!=h; j=(j+1)%len,k++) { result[k] = Math.max(result[k-1],nums[j]+result[k-2]); } return result[len-2]; } }
学习之处:
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4534787.html