zoukankan      html  css  js  c++  java
  • leetcode198. House Robber

     

    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.

    Example 1:

    Input: [1,2,3,1]
    Output: 4
    Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
                 Total amount you can rob = 1 + 3 = 4.

    Example 2:

    Input: [2,7,9,3,1]
    Output: 12
    Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
                 Total amount you can rob = 2 + 9 + 1 = 12.
    

     
    一直都不清楚动态规划,看了一些视频还是懵懵懂懂的感觉,在leetcode上做了一道DP的题,记录一下
    在做这题时,也看了别人的代码,自己太弱,一直看不懂为啥那样写,懂别人思路,不懂别人为啥那样写代码。。。。
    自己写了一个代码,运行成功。
    思路:用一个数组dp记录从开始到现在偷到的钱的总数。dp[i]代表前i家中能偷到的最大钱数。dp[n]即为所有的前N家能偷到的最大钱数,也即为所求结果。
    先记录nums中前两个的钱数。然后用一个循环从第三个开始,求能偷到的最大钱数。偷到第三家时的最大钱数,有两种可能,第一家的钱+第三家的钱或者是第二家的钱,这两个中去一个最大值,就是前三家中能偷到的最大钱数
    class Solution {
    public:
        int rob(vector<int>& nums) {
            int n = nums.size();
            if (!n) return 0;
            int dp[n];//dp就代表到达n时的最大价值
            dp[0] = nums[0];
            if (n < 2) {
                return dp[n - 1];
            }
            dp[1] = max(nums[0], nums[1]);
            for (int i = 2; i < n; i++) {
                dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]);
            }
            return dp[n - 1];
    
        }
    };

    Submission Result: Accepted

     
     
  • 相关阅读:
    git 基本使用
    docker下rabbitMQ高可用集群部署
    成长路上破局思维:工具化时间管理
    图解Elasticsearch的核心概念
    先森林后树木:Elasticsearch各版本升级核心内容必看
    JRebel 破解最简单的使用
    POA理论:不要被你的目标欺骗了你
    读了《跃迁-成为高手的技术》我的工资翻倍了
    微信头像地址失效踩坑记附带方案
    如何做程序员喜欢的测试妹子?
  • 原文地址:https://www.cnblogs.com/gousheng/p/9366830.html
Copyright © 2011-2022 走看看