zoukankan      html  css  js  c++  java
  • 13.House Robber

    题目描述:

    You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that 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.

    这是一道典型的动态规划题目。实质上是给定一个数组,寻找出数组中元素相加得到的最大结果。唯一不同的地方在于,这里选取的元素不能是相邻元素。对于这一特点,可以用求余操作来实现。

    代码如下:

    class Solution {
      public:
        int rob(vector<int>& nums) {
          int n = nums.size();
          int a=0;
          int b=0;
          for(int i=0;i<n;i++){
            if(i%2==0){
              a=max(a+nums[i],b);
            }
            else{
              b=max(a,nums[i]+b);
            }
          }
          return max(a,b);
        }
    };

     
  • 相关阅读:
    Codeforces
    Codeforces
    SCUT
    Codeforces
    Codeforces
    poj 2229 Sumsets(类似于n的m划分)
    poj 1742 Coins(多重背包)
    hdu 2159FATE(完全背包)
    NOIP 普及组 2014 比例简化
    2018.10.2浪在ACM 集训队第三次测试赛
  • 原文地址:https://www.cnblogs.com/sarahp/p/7080902.html
Copyright © 2011-2022 走看看