LeetCode动态规划198. House Robber思路解析

来源:互联网 发布:linux初学者入门书籍 编辑:程序博客网 时间:2024/05/21 13:55

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
原创粉丝点击