[leetcode-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.

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

 

 

 思路:
如果没有首和尾想连的限制的话,可以得到如下递推公式:  dp[i] = max(dp[i-2]+nums[i],dp[i-1 ]);

加上首和尾相连限制,那么也就是说首和尾最多只取一个,需要分别比较只取首或者只取尾的情况。

int rob2(vector<int>& nums,int start,int end)
    {
        int n = nums.size();
        vector<int>dp(n);
        if (start == end)return nums[start];
        if (start + 1 == end)return max(nums[start], nums[end]);         

        dp[start] = nums[start];
        dp[start + 1] = max(nums[start], nums[start+1]);

        for (int i = start+2; i <= end;i++)
        {
            dp[i] = max(dp[i-2]+nums[i],dp[i-1]);
        }

        return dp[end];
    }
    int rob2(vector<int>& nums)
    {
        int n = nums.size();
        if (nums.empty())return 0;
        if (n == 1)return nums[0];
        if (n == 2)return max(nums[0],nums[1]);
        if (n == 3)return max(nums[0], max(nums[1],nums[2]));

        //int r1 = nums[0] + rob2(nums,2,n-2);
        //int r2 = nums[1] + rob2(nums, 3, n - 1);//不对
        
        int r1 = rob2(nums, 1, n - 1);
        int r2 = rob2(nums, 0, n - 2); 
        return max(r1, r2);
    }

 

转载于:https://www.cnblogs.com/hellowooorld/p/7234772.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值