Leetcode 213. House Robber II

来源:互联网 发布:知乎b站三国演义 编辑:程序博客网 时间:2024/06/08 02:54

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.

s思路:
1. 之前的问题是,抢劫的路线是有端点的,也就是说有明显的左右边界。现在的问题,由于从直线变成换环线,左右不在有明显的边界了。怎么入手呢?
2. 没有端点,那是我们根据题意很容易就看到没有端点的外表。只要一转念,就可重新看到有端点的现象,比如:我们可以把换线断开即可有端点,具体操作就是:第一个端点永远不取,那么就变成了直线了;仅这么还不够,还要讨论如果最后一个点也永远不取,得到的最大值,两个最大值的较大的就是最后结果!
3. 因此,上面意味着,不同的位置断开,那么一个环线的问题就转换成两个直线的问题,同时由于每个直线的问题都可以用相同的代码实现,因此,写成一个子函数,这样调用两次就可以了。
4. 关键的问题是,如何想到从环线变成直线的呢?其实直线、环线本来就没有什么区别,也不是说没区别,是区别没有想象这么大,因为在我的思维里,仿佛完全把直线和环线给isolate,完全区别对待。这个思维就不正确,因为只看到了事物的表面现象,不承认事物可以相互转换,因此这种简单的、分割的、静态的死气沉沉的思维,必将成为阻碍我们看到事物见联系的一堵墙、一个强大的barrier。思维的墙很多,需要一扇一扇的来打破,当然也不用这么累,如果学会从不同角度看问题,对如下事实充满信念:任何事物见都没有没有独立的、不变的、永恒的界限,或者说,任何事物都是相互关联的,只要我们站的角度合适,都可以看到两件事的bond!
5. 回到这道题,环线不会直接等于直线的,这是明显的。但这个命题的精确的说法是:一条环线不等于一条直线,但一条环线却可以等于两条直线,只要我们分情况讨论,就可以做到!

//方法1:从一条环线中看出两条直线class Solution {public:     int helper(vector<int>& nums,int start,int end){        //        if(start>end) return 0;        int pre=0,cur=nums[start],mx=cur;        for(int i=start+1;i<=end;i++){            int tmp=cur;            cur=max(pre+nums[i],cur);            pre=tmp;                mx=max(cur,mx);        }        return mx;    }    int rob(vector<int>& nums) {        //        int n=nums.size();        if(n==1) return nums[0];        return max(helper(nums,1,n-1),helper(nums,0,n-2));            }};
0 0
原创粉丝点击