zoukankan      html  css  js  c++  java
  • [LeetCode] House Robber 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.

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

    https://leetcode.com/problems/house-robber-ii/

    LeetCode这是一天一道题的节奏吗?这道题就是在上一题的基础上加了一个条件,变成了环,所以如果抢了第一家,就不能抢最后一家。所以我们可以分别计算抢了从第二家到最后一家与抢从第一家到倒数第二家的最大值,取两个值中更大的那个就是结果。

     1 class Solution {
     2 public:
     3     int rob(vector<int> &num) {
     4         if (num.size() == 0) return 0;
     5         if (num.size() == 1) return num[0];
     6         vector<int> dp(num.size());
     7         //抢第一家到倒数第二家的最大值
     8         dp[0] = num[0];
     9         for (int i = 1; i < num.size() - 1; ++i)
    10             dp[i] = max(dp[i-1], (i == 1 ? 0 : dp[i-2]) + num[i]);
    11         int res = dp[num.size()-2];
    12         //抢第二家到最后一家的最大值
    13         dp[1] = num[1];
    14         for (int i = 2; i < num.size() ; ++i)
    15             dp[i] = max(dp[i-1], (i == 2 ? 0 : dp[i-2]) + num[i]);
    16         //返回两者较大的一个    
    17         return max(res, dp[num.size()-1]);
    18     }
    19 };
  • 相关阅读:
    python做一个数独小游戏
    通过进程快照枚举进程的信息
    单向链表 malloc与free
    指针常量&指向常量的指针
    变量在不同区域的默认初始值
    数组指针和指针数组
    堆的首地址和堆的指针
    创建对象时,系统会自动调用构造函数和析构函数
    对象所占内存的大小与首地址
    范磊 C++ 第8章 指针
  • 原文地址:https://www.cnblogs.com/easonliu/p/4516557.html
Copyright © 2011-2022 走看看