leetcode 198|213. House Robber 1|2

来源:互联网 发布:蓝牙单片机 编辑:程序博客网 时间:2024/05/16 08:35

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.

线性动态规划

class Solution {public:    int rob(vector<int>& nums)     {         if(nums.size() == 0)            return 0;        else if(nums.size() == 1)            return nums[0];        else if(nums.size() == 2)            return max(nums[0], nums[1]);        else if(nums.size() == 3)            return max(nums[0] + nums[2], nums[1]);                nums[2] += nums[0];        for (int i = 3; i < nums.size(); i++)         {            nums[i] += max(nums[i-2], nums[i-3]);        }                    return max(nums[nums.size()-1], nums[nums.size()-2]);       }};

213. House Robber II

Note: This is an extension of House Robber.

After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street. 

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.

House Robber I的升级版. 
因为第一个element 和最后一个element不能同时出现. 则分两次call House Robber I. 
case 1: 不包括最后一个element. 
case 2: 不包括第一个element.
两者的最大值即为全局最大值

class Solution {public:     int rob_helper(vector<int>& nums)     {         if(nums.size() == 0)            return 0;        else if(nums.size() == 1)            return nums[0];        else if(nums.size() == 2)            return max(nums[0], nums[1]);        else if(nums.size() == 3)            return max(nums[0] + nums[2], nums[1]);                nums[2] += nums[0];        for (int i = 3; i < nums.size(); i++)         {            nums[i] += max(nums[i-2], nums[i-3]);        }                    return max(nums[nums.size()-1], nums[nums.size()-2]);       }    int rob(vector<int>& nums)     {        if (nums.size() == 0)            return 0;        else if (nums.size() == 1)            return nums[0];                vector<int> m1 = nums;        m1.erase(m1.begin());        vector<int> m2 = nums;        m2.pop_back();        return max(rob_helper(m1), rob_helper(m2));    }};



原创粉丝点击