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]);
        }
    };
  • 相关阅读:
    高斯模糊原理,算法
    SIFT算法详解
    第五章:状态图
    ANTLR4权威指南
    第八章:包图,组件图,部署图
    棋盘n皇后问题-递归
    普通页面引入React(使用和不使用JSX)
    浏览器环境
    DevTool-Network
    优化浏览器渲染
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4966188.html
Copyright © 2011-2022 走看看