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 };
  • 相关阅读:
    条件判断和循环
    list 和tuple的使用
    python的五大数据类型
    简单的一个程序,猜字游戏
    redhat7 nfs的配置以及auto自动挂载
    nmcli添加网卡 并且修改设备名字 添加IP地址
    RHEL7 系统ISCSI存储环境搭建
    Java分布式锁
    24个Jvm面试题总结及答案
    最新天猫3轮面试题目:虚拟机+并发锁+Sql防注入+Zookeeper
  • 原文地址:https://www.cnblogs.com/shellfishsplace/p/6046166.html
Copyright © 2011-2022 走看看