[leetcode] 198. House Robber

来源:互联网 发布:淘宝工装风店铺推荐 编辑:程序博客网 时间:2024/04/28 03:10

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 andit 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 tonightwithout alerting the police.

这道题是窃贼偷东西,不能偷相邻的两个房子,题目难度为easy。

针对第N个房子,偷这个房子的话第N-1个房子不能偷,这样偷得赃款就是第N-2个房子累计的赃款加上第N个房子的钱;不偷这个房子的话赃款数就是第N-1个房子累计的赃款,取这两个中大的那个作为到第N个房子为止可以偷得的最大赃款数。这样可以采用动态规划的方法递推出最终可以获取的最大赃款数。具体代码:

class Solution {public:    int rob(vector<int>& nums) {        if(nums.empty()) return 0;        vector<int> money(nums.size(), 0);        money[0] = nums[0];        for(int i=1; i<nums.size(); i++) {            money[i] = max(money[i-1], ((i>1)?money[i-2]:0)+nums[i]);        }        return money.back();    }};
另外,我们发现,到第N个房子累计的赃款数仅和第N-1和第N-2个房子的累计值有关,这样我们可以避免存储所有房子的赃款累计值,将空间复杂度降到O(1),具体代码:
class Solution {public:    int rob(vector<int>& nums) {        if(nums.empty()) return 0;        int money1 = 0, money2 = 0, money3 = 0;        for(int i=0; i<nums.size(); i++) {            money3 = max(money2, money1+nums[i]);            money1 = money2;            money2 = money3;        }        return money3;    }};

0 0
原创粉丝点击