• 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];
        }
    };
  • 相关阅读:
    acwing 164. 可达性统计(拓扑排序+位运算,bitset使用)
    csp 2020062 稀疏向量(双指针)
    acwing 二分图的最大匹配(匈牙利算法)
    acwing 860. 染色法判定二分图(dfs,bfs)
    acwing 1140. 最短网络(prim)
    acwing 3745. 牛的学术圈 I(构造)
    CF585F Digits of Number Pi
    剩余系建图
    P5445 [APIO2019]路灯
    P8097 [USACO22JAN] Farm Updates G
  • 原文地址:https://www.cnblogs.com/heyn1/p/10985071.html
Copyright © 2020-2023  润新知