[Leetcode] 198. House Robber 解题报告

来源:互联网 发布:w7内外网转换软件 编辑:程序博客网 时间:2024/05/20 06:52

题目

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个位置可以获得的最大抢劫钱数,则有如下两种情况:

1)如果要抢当前家庭,则上家不能抢,因此受益为dp[i + i] = dp[i - 1] + nums[i + 1];

2)如果不抢当前家庭,则受益同其前驱,即dp[i + 1] = dp[i]。注意dp[i]并不一定意味着一定抢劫了第i家。

因此状态转移方程为:dp[i + 1] = max(dp[i - 1] + nums[i + 1], dp[i])。算法的时间复杂度是O(n),空间复杂度是O(n)。但是从状态转移方程来看,dp[i+1]只和dp[i-1]以及dp[1]相关,因此可以进一步优化,将空间复杂度降低到O(1)。下面是优化后的代码片段。

代码

class Solution {public:    int rob(vector<int>& nums) {        if (nums.size() == 0) {    return 0;        }    if (nums.size() == 1) {    return nums[0];    }    int value0 = nums[0], value1 = max(value0, nums[1]);    for (size_t i = 2; i < nums.size(); ++i) {    int max_value = max(value0 + nums[i], value1);    value0 = value1;    value1 = max_value;    }    return value1;    }};