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

  • 相关阅读:
    四种数据库随机获取10条数据的方法
    古诗词
    一份 Spring Boot 项目搭建模板
    2020年只剩两个月,今年你是怎么过的?
    关于使用LocalDateTime进行存储,时间相差比较多的问题。
    项目中常用的19条MySQL优化
    SpringBoot注解大全
    JDK8的LocalDateTime用法
    linux代理上网5分钟搞定
    SQL简单语句作用
  • 原文地址:https://www.cnblogs.com/dapeng-bupt/p/8926554.html
Copyright © 2011-2022 走看看