LeetCode 213. House Robber II (Medium)

来源:互联网 发布:淘宝电影票 编辑:程序博客网 时间:2024/05/19 10:33

题目描述:

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.

题目大意:有很多栋房子,房子成环形,要偷这些房子里面的钱,不能连续偷两个房子(会被抓),问最多能偷多少钱。

思路:DP。分情况,偷不偷第1栋房,偷就算1到n - 1栋的最大值,不偷就算2到n栋的最大值,求这两个的最大值即可。

c++代码:

class Solution {public:    int rob(vector<int>& nums) {        if (nums.size() == 0)            return 0;        else if (nums.size() == 1)            return nums[0];        else            return max(myRob(nums, 0, nums.size() - 1), myRob(nums, 1, nums.size()));    }    int myRob(vector<int>& nums, int l, int r)    {        int prev = 0;        int pprev = 0;        for (size_t i = l; i < r; ++i)        {            int temp = prev;            prev = max(nums[i] + pprev, prev);            pprev = temp;        }        return prev;    }};
原创粉丝点击