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 };
  • 相关阅读:
    蓝桥杯--芯片测试
    蓝桥杯--FJ的字符串
    win8 js 没反应
    winform win8 js checkbox互动
    win8 GridView
    wcf服务引用无实体类对象
    arcgis 接口转换与.Net框架
    win8 链接
    分页控件
    Oracle 分页查询存储过程
  • 原文地址:https://www.cnblogs.com/easonliu/p/4516557.html
Copyright © 2011-2022 走看看