【LeetCode】198. House Robber

来源:互联网 发布:php支付宝当面付demo 编辑:程序博客网 时间:2024/04/29 00:53

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.

思路一:A[i][0]表示第i次没有抢劫,A[i][1]表示第i次进行了抢劫,即A[i+1][0] = max(A[i][0], A[i][1]).. 那么rob当前的house,只能等

于上次没有rob的+money[i+1], 则A[i+1][1] = A[i][0]+money[i+1].实际上只需要两个变量保存结果就可以了,不需要用二维数组

思路二:找到递推关系:maxV[i] = max(maxV[i-2]+num[i], maxV[i-1])

class Solution {public:    int rob(vector<int>& nums) {        int no_rob = 0;        int rob = 0;        for(int i = 0; i < nums.size(); i++)        {            int tmp = no_rob;            no_rob = max(no_rob, rob);            rob = tmp + nums[i];        }        return max(no_rob, rob);    }};


0 0