温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

leetCode 213. House Robber II | Medium | Dynamic Programming

发布时间:2020-07-13 09:16:14 来源:网络 阅读:292 作者:313119992 栏目:开发技术

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. House Robber 的升级版。之前已经做过。链接如下:

http://qiaopeng688.blog.51cto.com/3572484/1844956

第一版的房间形成的街道是一条直线。

第二版的房间形成的街道是成一个圆。


思路:

因为圆的首尾是相邻的,所以选首不能选尾,选尾不能选首。所以有了下面的思路。

  1. 求出不选尾的最大值。也就是数组中a[0]到a[N-1]求出最大值。

  2. 求出不选首的最大值。也就是数组中a[1]到a[N]求出最大值。

  3. 比较1,2的最大值,然后得到最终结果。


代码如下:

class Solution {
public:
    int rob(vector<int>& nums) 
    {
        int numLength = nums.size();
    	if (nums.empty())
    		return 0;
    	if (1 == numLength)
    		return nums[0];
    	if (2 == numLength)
    		return nums[0] > nums[1] ? nums[0] : nums[1];
    	int *maxV1 = new int[nums.size() - 1];// 0---nums.size()-2
    	int *maxV2 = new int[nums.size() - 1];// 1---nums.size()-1
    	int result = 0;
    	maxV1[0] = nums[0];
    	maxV1[1] = nums[0] > nums[1] ? nums[0] : nums[1];
    
    	for (int i = 2; i < nums.size() - 1; ++i)
    	{
    		maxV1[i] = max(maxV1[i - 2] + nums[i], maxV1[i - 1]);
    	}
    
    	maxV2[0] = nums[1];
    	maxV2[1] = nums[1] > nums[2] ? nums[1] : nums[2];
    	for (int i = 3; i < nums.size(); ++i)
    	{
    		maxV2[i - 1] = max(maxV2[i - 3] + nums[i], maxV2[i - 2]);
    	}
    
    	result = max(maxV1[nums.size() - 2], maxV2[nums.size() - 2]);
    
    	delete maxV1;
    	delete maxV2;
    	maxV1 = NULL;
    	maxV2 = NULL;
    	return result;
    }
};

总结:

代码瞬息万变,解决万千问题。哈哈哈哈。有意思。

2016-08-31 23:41:18

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI