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];
        }
    };
    
  • 相关阅读:
    KBEngine源码:EntityCall
    skynet 学习笔记-sproto模块(2)
    mongodb:为什么用mongodb
    编写高效服务器程序,需要考虑的因素
    b+树
    mysql:架构
    超越函数/微分方程 /积分中的技术/级数
    积分从入门到放弃<2>
    PyQt4 / PyQt5
    图形学算法:
  • 原文地址:https://www.cnblogs.com/pk28/p/8483780.html
Copyright © 2011-2022 走看看