leetcode之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.
题目描述:一条街上有一排房子,每个房子中有一定数额的金钱,你不能同时打劫相邻的房子,求一晚上能打劫的最大“收益”。
思路:动态规划问题,记g[i]表示打劫到第i家为止的最大“收益”,那么相应的递推关系如下:
g[i] = max(g[i-1], g[i-2]+nums[i]),即打劫到第i-1家时的最大收益与打劫到第i-2家的最大收益加上打劫第i家获得的金钱(nums[i])。算法的时间复杂度为O(n),空间复杂度为O(1)(调优后的结果),代码如下:

class Solution {
public:
    int rob(vector<int>& nums) {
        int len = nums.size();
        if(len == 0)
            return 0;
        if(len == 1)
            return nums[0];
        int g, t;
        g = t = 0;//g表示g[i],t表示g[i-2]
        for(int i = 0; i < len; ++i){
            int tmp = g;
            g = max(g, t+nums[i]);
            t = tmp;
        }
        return g;
    }
};

该题的扩展,即House Robber II,此时多了一重限制,即所有的房子围成一个圈,也就是第一家和最后一家不能同时打劫,那么分别计算打劫第一家或者打劫最后一家的最大“收益”(计算方法同House Robber) ,然后取两者的最大值即可,代码如下:

class Solution {
public:
    int rob1(vector<int>& nums, int left, int right) {
        int g, t;
        g = t = 0;
        for(int i = left; i < right; ++i){
            int tmp = g;
            g = max(g, t+nums[i]);
            t = tmp;
        }
        return g;
    }
    int rob(vector<int>& nums) {
        int len = nums.size();
        if(len == 0)
            return 0;
        if(len == 1)
            return nums[0];
        return max(rob1(nums, 0, len-1), rob1(nums, 1, len));
    }
};

你可能感兴趣的:(leetcode)