zoukankan      html  css  js  c++  java
  • LeetCode OJ:House Robber II(房屋窃贼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 arearranged 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来解决,代码如下所示:

    class Solution {
    public:
        int rob(vector<int>& nums) {
            if(!nums.size()) return 0;
            if(nums.size() == 1) return nums[0];
            vector<int> ret1, ret2;
            ret1.resize(nums.size());
            ret2.resize(nums.size());
            ret1[0] = nums[0];
            ret2[1] = nums[1];
            for(int i = 1; i < nums.size() - 1; ++i){
                ret1[i] = max((i == 1 ? 0 : ret1[i - 2]) + nums[i], ret1[i - 1]);
            }
            for(int i = 2; i < nums.size(); ++i){
                ret2[i] = max((i == 2 ? 0 : ret2[i - 2]) + nums[i], ret2[i - 1]);
            }
            return max(ret1[nums.size() - 2], ret2[nums.size() - 1]);
        }
    };
  • 相关阅读:
    Forword: ssh server for windows
    多浏览器测试
    GMT PST Beijing 时间
    Localization process
    【转】CentOS下配置PXE+Kickstart无人值守安装(Howto install CentOS through PXE+KickStart)
    CI hudson 远程部署
    s3cmd 安装使用指南
    Git
    关于Request.Form获取listbox所有项的问题
    Assembly.LoadFrom 与Assembly.Load 与 Assembly.LoadFile
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4966188.html
Copyright © 2011-2022 走看看