zoukankan      html  css  js  c++  java
  • [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);
        }
  • 相关阅读:
    推荐网址:Response.WriteFile Cannot Download a Large File
    为什么是 My?
    Fox开发杂谈
    DCOM配置为匿名访问
    连接到运行 Windows 98 的计算机
    OO面向对象以后是什么
    Com+的未来是什么?
    fox 表单和类库的加密及修复
    来自 COM 经验的八个教训
    VFP的加密问题
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/7234772.html
Copyright © 2011-2022 走看看