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 };
  • 相关阅读:
    去掉Win10中的“此电脑”中的6个默认文件夹的方法
    Fastboot驱动及安装
    Fastboot驱动及安装
    JNI+NDK编程总结
    JNI+NDK编程总结
    20194742自动生成四则运算题第一版报告
    读构建之法现代软件工程随笔
    想法或创意
    ubuntu控制台乱码
    Java 为什么不支持多继承?
  • 原文地址:https://www.cnblogs.com/shellfishsplace/p/6046166.html
Copyright © 2011-2022 走看看