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.

    题目大意

    给定一个数组,从数组中挑选出一些数字使得数字最大, 要求不能挑选任意两个相邻的数字。

    示例

    E1

    Input: [1,2,3,1]
    Output: 4

    E2

    Input: [2,7,9,3,1]
    Output: 12

    解题思路

    动态规划问题,设数组dp[n],其中dp[i]代表:到第i个数字可以选到的从0到i的最大组合的数值。

    利用dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]),(PS:式子表示dp[i]的最大值为i - 1的最大值或i - 2的最大值加i的值)

    即可知道dp[n - 1]为所求得的最后结果。

    复杂度分析

    时间复杂度:O(n)

    空间复杂度:O(n)

    代码

    class Solution {
    public:
        int rob(vector<int>& nums) {
            int n = nums.size();
            //若n为0,1,2进行判断
            if(n == 0)
                return 0;
            if(n <= 2) {
                return n == 1 ? nums[0] : max(nums[0], nums[1]);
            }
            
            vector<int> dp(n + 1, 0);
            dp[0] = nums[0];
            dp[1] = max(nums[0], nums[1]);
            //进行dp最优状态转移
            for(int i = 2; i < n; i++) {
                dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]);
            }
            
            return dp[n - 1];
        }
    };
  • 相关阅读:
    如何注册一个ens域名
    storj
    Polygon
    拜占庭容错
    10秒钟完成metamask上任意公链主网添加
    Logistic Regression
    Normal Equations
    神经网络学习笔记 lecture3:The backpropagation learning proccedure
    Three Types of Learning
    Exercise: Logistic Regression and Newton's Method
  • 原文地址:https://www.cnblogs.com/heyn1/p/10985071.html
Copyright © 2011-2022 走看看