zoukankan      html  css  js  c++  java
  • leetcode 198

    198. 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.

    求出一个数列中不相邻的的组合的各个数相加的的最大值。

    采用动态规划的思想。

    对于第i个房间我们的选择是偷和不偷, 

    如果决定是偷 则第i-1个房间必须不偷 那么 这一步的就是 re[i] = nums(i-1) + re[i-2] , 

    假设re[i]表示打劫到第i间房屋时累计取得的金钱最大值.

    如果是不偷, 那么上一步就无所谓是不是已经偷过, re[i] = re[i -1 ], 因此 re[i] =max(re[i-2] + nums(i-1), re[i-1] );  

    利用动态规划,状态转移方程:re[i] = max(re[i - 1], re[i - 2] + nums[i - 1]).

    代码如下:

     1 class Solution {
     2 public:
     3     int rob(vector<int>& nums) {
     4         int n = nums.size();
     5         if(n == 0)
     6         {
     7             return 0;
     8         }
     9         int * re = new int[n+1];
    10         re[0] = 0;
    11         re[1] = nums[0];
    12         for(int i = 2; i < n+1; i++)
    13         {
    14             re[i] = max(re[i-1], re[i-2] + nums[i-1]);
    15         }
    16         return re[n];
    17     }
    18 };
  • 相关阅读:
    delphi Base64
    delphi 注册表
    二、Spring Boot项目的三种启动方式
    Junit的运行流程以及Junit常用注解
    eclips集成单元测试
    六、AcriveMQ集群配置的三种方式,以及组合实现
    五、Sping 中实现简单实现activeMQ
    三、简单实现activeMQ发送消息
    二、安装ActiveMQ消息中间件
    一、消息中间件基础
  • 原文地址:https://www.cnblogs.com/shellfishsplace/p/6046166.html
Copyright © 2011-2022 走看看