[leetcode] 198. House Robber 解题报告

题目链接:https://leetcode.com/problems/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[],用于保存每一个位置最大的抢劫钱数。遍历数组中的每一个数,每次会有两种情况

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

2. 如果不抢当前家庭,则收益为抢上一家的收益,即为dp[i+1] = dp[i];

因此可以得到状态转移方程为:

dp[i+1] = max(dp[i-1] + nums[i], dp[i]);

时间复杂度为O(n),空间复杂度为O(n)。

代码如下:

class Solution {
public:
    int rob(vector<int>& nums) {
        if(nums.size() == 0)
            return 0;
        vector<int> result(nums.size()+1, 0);
        result[1] = nums[0];
        for(int i = 1; i< nums.size(); i++)
            result[i+1] = max(nums[i] + result[i-1], result[i]);//是否抢当前这家要看哪个收益更大
        return result[nums.size()];
    }
};


你可能感兴趣的:(LeetCode,算法,dynamic,programming,动态规划)