• leetcode 213. House Robber II


    You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

    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.

    Example 1:

    Input: [2,3,2]
    Output: 3
    Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2),
                 because they are adjacent houses.
    

    Example 2:

    Input: [1,2,3,1]
    Output: 4
    Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
                 Total amount you can rob = 1 + 3 = 4.

    题目大意:房子以圆形布置,小偷同时偷相邻的房屋就会报警。求在不报警的前提下,能偷到的最多钱数。

    分析:由于圆形,第0家和第n家(最后一家)不能同时被偷,因此分两种情况转化为房子呈直线布置的情况就好了(0, ..., n - 1)和(1, ..., n)

     1 class Solution {
     2 public:
     3     int rob(vector<int>& nums) {
     4         int len = nums.size();
     5         if (len == 0)
     6             return 0;
     7         if (len == 1)
     8             return nums[0];
     9         return max(robOriginal(nums, 0, len - 2, len), robOriginal(nums, 1, len - 1, len));
    10     }
    11 private:
    12     int robOriginal(vector<int> nums, int l, int r, int len) {
    13         int prev = 0, cur = 0;
    14         for (int i = l; i <= r; i++) {
    15             int temp = max(cur, prev + nums[i]);
    16             prev = cur;
    17             cur = temp;
    18         }
    19         return cur;
    20     }
    21 };
  • 相关阅读:
    JS解析XML文件和XML字符串
    查询优化的方法
    Oracle 常用操作
    取得同一网段内的IP和MAC地址!
    域名知多少?
    Oracle 数据库链路 同义词
    提高查询速度的方法【百万级以上数据】
    ExtJs学习之路从Grid中得到数据
    一个左边停靠且可以展开和隐藏的菜单【Jquery插件】
    Go流程控制
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/11467090.html
Copyright © 2020-2023  润新知