House Robber II

题目

原题

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.

思路

这道题是House Robber(链接:https://leetcode.com/problems/house-robber/)的升级版本.
即所给定的nums构成了环.
由于每个house最多被rob一次, 设len=nums.size(),
所以这个环只对nums[0]和nums[len-1]起作用.
即如果选择了nums[0], 就不能选择了nums[len-1];
如果选择了nums[len-1], 就不能选择nums[0].
所以该问题就变了了House Robber的两个子问题的结果最大值.
ans=max(rob(nums[0,...,len-2), rob(nums[1,...,len-1)). 
其中rob为House Robber问题的解.
具体看代码.

code

class Solution {
public:
    int rob_helper(const vector<int>& nums, const int s, const int e) {
        int len = e - s + 1;
        vector<int>res(len, 0);
        res[0] = nums[s];
        res[1] = max(nums[s], nums[s + 1]);
        for(int i = s + 2; i <= e; i++) {
            res[i - s] = max(res[i - s - 2] + nums[i], res[i - s - 1]);
        }
        return res[len - 1];
    }

    int rob(vector<int>& nums) {
        int len = nums.size();
        if(len <= 0) return 0;
        if(len <= 1) return nums[0];
        // Include the first one of nums without the last one.
        int f = rob_helper(nums, 0, len - 2);
        // Include the last one of nums without the first
        int s = rob_helper(nums, 1, len - 1);
        return max(f, s);
    }
};

你可能感兴趣的:(House Robber II)