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));
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值