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.

    题目大意:给一个数组,可以取其中的若干个,但是不能取相邻的两个,问能得到的最大值。
    思路:动态规划思想,设dp[i]表示前i个数能取到的最大值,那么dp[i] = dp[i-1]或者dp[i] = dp[i-2]+num[i]即对第i个数可以选择取或不取,类似背包。

    class Solution {
    public:
        int rob(vector<int>& nums) {
            if (nums.size() == 0) return 0;
            int n = nums.size();
            vector<int> dp(n);
            dp[0] = nums[0];
            dp[1] = max(nums[1], nums[0]);
            for (int i = 2; i < n; ++i) {
                dp[i] = max(dp[i-1],dp[i-2]+nums[i]);
            }
            return dp[n-1];
        }
    };
    
  • 相关阅读:
    133
    132
    131
    130
    129
    128
    2019.10.16考试解题报告
    2019.10.15考试解题报告
    洛谷 P1352 没有上司的舞会
    2019.10.13考试解题报告
  • 原文地址:https://www.cnblogs.com/pk28/p/8483780.html
Copyright © 2011-2022 走看看