LeetCode动态规划198. 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.


思路点拨

递归思想:
抢劫从编号为cur房子开始,到end结束,所获得的利益为:
a)在抢劫第cur房子时,int robed=nums[cur]+rob(cur+2,end),
b) 不抢劫cur房子时,int nonRobed=rob(cur+1,end)
c)返回max(robed,nonRobed),该值作为 抢劫起始编号为cur,结束为end的获得的最大利益。


c++代码实现

class Solution {
public:
    int recurse(vector<int>& table, vector<int>& nums, int cur, int end)
    {
        if (cur> end)
        {
            return 0;
        }

        // 对于table中曾经通过递归确定了的值,不再判断是否rob
        if (-1 != table[cur])
        {
            return table[cur];
        }

        // 如果是rob,就把当前值加上 以cur+2开始的新的nums用来递归判断得到的最大值 作为rob时得到的最大值
        int robed = nums[cur] + recurse(table, nums, cur + 2, end);

        // 如果是rob,就把 以cur+1开始的新的nums用来递归判断得到的最大值 作为没rob时得到的最大值
        int nonRobed = recurse(table, nums, cur + 1, end);

        // 把2种情况对应的最大值中较大的一个作为 “强盗从当前house一直到street末尾的house可获得的最大值”
        table[cur] = (robed > nonRobed) ? robed: nonRobed;

        return table[cur];
    }

    int rob(vector<int>& nums) {
        if (nums.empty())
        {
            return 0;
        }
        int len = nums.size();
        if (1 == len)
        {
            return nums[0];
        }

        // 创建一个与house数量一致的table,table[i]表示从下标为i的house开始到最后一个house强盗可获得的最大财富值,初始化为-1,表示table[i]还未计算
        vector<int> table(len, -1);

        // 递归判断每个table[i], 最后强盗所能获得的最大财富值就是table[0] 
        return recurse(table, nums, 0, len -1);
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值