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];
        }
    };
    
  • 相关阅读:
    Evanyou Blog 彩带
    Evanyou Blog 彩带
    复合类型的声明——是int *p还是int* p
    指针
    引用
    变量声明和变量定义
    C++内置类型如何存放于计算机内存中
    C++的几种字符类型
    第四章 表达式
    ++i && i++
  • 原文地址:https://www.cnblogs.com/pk28/p/8483780.html
Copyright © 2011-2022 走看看