leetcode 198. House Robber

来源:互联网 发布:淘宝民族风女装品牌 编辑:程序博客网 时间:2024/06/05 01:19

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;
        int premax=nums[0];
        int prepremax=0;
        int curmax=nums[0];
        for(int i=1;i<nums.size();i++)
        {
            if((prepremax+nums[i])>premax)
            curmax=prepremax+nums[i];
            else
                curmax=premax;
           prepremax=premax;
            premax=curmax;
        }
        return curmax;
    }
};

思路:

这是一道典型的动态规划,用money[i]表示从第1座房子到第i座房子能抢到的最多的钱,那么money[i] = max(money[i - 2] + nums[i], money[i - 1])。

每次循环更新该点前面一个的最大值和该点前面两个的最大值和此时该点的最大值。

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.


class Solution {
public:
    int rob(vector<int>& nums) {
        if(nums.size()==0)
        return 0;
        if(nums.size()==1)
            return nums[0];
        int premax1=nums[0];
        int prepremax1=0;
        int curmax1=nums[0];
        int curmax2=nums[1];
        int premax2=nums[1];
        int prepremax2=0;
        for(int i=1;i<nums.size()-1;i++)
        {
            if((prepremax1+nums[i])>premax1)
            curmax1=prepremax1+nums[i];
            else
                curmax1=premax1;
           prepremax1=premax1;
            premax1=curmax1;
        }
    for(int i=2;i<nums.size();i++)
        {
            if((prepremax2+nums[i])>premax2)
            curmax2=prepremax2+nums[i];
            else
                curmax2=premax2;
           prepremax2=premax2;
            premax2=curmax2;
        }
        if(curmax1>curmax2)
            return curmax1;
        else 
            return curmax2;
    }
};

思路:

一个圆上有n座房子,其它条件都一样,只是第1座房子和第n座房子变成相邻的了,也就是说不能同时抢了,那么最优解就变成 第1座房子到第n-1座房子能抢的最多的钱 或者 第2座房子到第n座房子能抢的钱了。


原创粉丝点击