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];
    }
};
原文地址:https://www.cnblogs.com/pk28/p/8483780.html