zoukankan      html  css  js  c++  java
  • LeetCode 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.

    本题是一道简单的动态规划题目,本质上是求一个数组中不连续数字的最大和,状态转移方程如下:

    设置maxV[i]表示到第i个房子位置时的最大收益。

    递推关系为maxV[i] = max(maxV[i-2]+num[i], maxV[i-1])  第一项表示不抢第i-1个房子,那么可以抢第i个房子;第二项表示不抢第i个房子,那么此时收益等于在i-1个房子的收益

    注:可能会对上述递推关系产生疑问,是否存在如下可能性,maxV[i-1]并不含num[i-1]?

    结论是,在这种情况下maxV[i-1]等同于maxV[i-2],因此maxV[i-2]+num[i]更大,转移方程依然成立。

    代码如下:

     1 class Solution {
     2 public:
     3     int rob(vector<int>& nums) {
     4         int n = nums.size();
     5         vector<int> dp(n,0);
     6         if (n == 0)
     7             return 0;
     8         else if (n == 1 )
     9              return nums[0];
    10         else if (n == 2)
    11             return max(nums[0],nums[1]);
    12         else
    13         {
    14             dp[0] = nums[0];
    15             //dp[1] = nums[1];//;
    16              dp[1] = max(nums[0],nums[1]);   //这里要小心
    17             for (int i = 2; i < n; i++)
    18             {
    19                 dp[i] = max(dp[i-1],dp[i-2]+nums[i]);
    20             }
    21         }
    22         return dp[n-1];
    23         
    24     }
    25 };

    推荐一篇非常精彩的讲解这道题的博客,注意看评论,http://www.cnblogs.com/grandyang/p/4383632.html

  • 相关阅读:
    【Linux高频命令专题(7)】rm
    【Linux高频命令专题(6)】mkdir
    【mongoDB运维篇①】用户管理
    【Linux高频命令专题(5)】rmdir
    【mongoDB中级篇②】索引与expain
    【mongoDB中级篇①】游标cursor
    Lua中的字符串函数库
    ngx_lua 随笔
    Nginx与Lua
    MAC 上搭建lua
  • 原文地址:https://www.cnblogs.com/dapeng-bupt/p/8926554.html
Copyright © 2011-2022 走看看