• 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);
        }
    };

     
  • 相关阅读:
    做统计图的好工具
    QueryBuildRange中的表达式
    四种方式话Equal
    QueryBuildRange的空值
    GetHashCode()初探
    X++中的字符串操作函数
    寻找缺陷的方法
    字程序级别的重构
    代码大全的方向
    多线程啊
  • 原文地址:https://www.cnblogs.com/sarahp/p/7080902.html
Copyright © 2020-2023  润新知