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.

Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.

解题思路

很明显,这是一道动态规划的题目,在tag中也标明了。
可以这样分析:
先说明两个数组的含义:
rob[N]:表示到第N家商户的最大化收益
notRob[N]:表示在不抢劫第N家商户的前提下的最大化收益。
继续…..
如果这条街道上只有一家商户,为了利益最大化,你决定抢,则为rob[0] = num.at(0),但是你忽然发善心,不抢了,则notRob[0] = 0.
之后这条街道繁荣起来了,商户变多,假设有N家商户,此时你已经“处理(抢或者不抢巴拉巴拉)”了前N-1家商户,来到了第N家商户的门前。那么摆在你面前的选择题如下:
1、对第N家商户不抢,则你的最大化收益就是截止到第N-1商户的收益,即notRob[N] = r[N - 1];
rob[N] = rob[N - 1];
2、假设你要对第N家商户动手,那么有一个重要的前提就是:你没有抢劫第N-1家商户。则收益为
rob[N] = notRob[N - 1] + num.at(N) > rob[N] ? notRob[N - 1] + num.at(N) : rob[N];

按照这个规则你一直抢到最后一家商户,比较一下notRob[N]和rob[N]哪个比较大就ok了。

(PS:可能还要压缩的空间。。但是这样比较直观。。)

class Solution {
public:
    int * r;
    int * nr;

    int rob(vector<int> &num) {
        if(0 == num.size())
        {
            return 0;
        }

        r = new int[num.size()];
        nr = new int[num.size()];

        //第一家的值就是默认的
        r[0] = num.at(0);
        nr[0] = 0;

        //以下把day看成loc就好,就是挨个从到到位打劫一遍
        for(int day = 1; day <= num.size() - 1; ++day)
        {
            //不抢劫的最大化值
            nr[day] = r[day - 1];
            //抢劫的最大化值
            r[day] = nr[day - 1] + num.at(day);
            if(r[day - 1] > r[day])
            {
                r[day] = r[day - 1];
            }
        }

        int re = nr[num.size() - 1];
        if(re < r[num.size() - 1])
        {
            re = r[num.size() - 1];
        }

        return re;
    }
};

你可能感兴趣的:(oj,基础算法,leetcode)