Leetcode-198. House Robber

来源:互联网 发布:js遍历数组中部分元素 编辑:程序博客网 时间:2024/04/30 21:45

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.

给出一个vector,不能连续的两个vector相加,求最后这样的一个vector的最大加和返回值。

关键思路是:当前点 i 与 第 i - 2 个的产出结果的值相加,能否大于 第 i - 1 个的产出结果,要是大于的话,就采用此策略,即第 i 点被采纳加入,若不行,则采用 第 i -1 个的产出结果作为第 i 的产出结果。

本题主要参考:http://www.cnblogs.com/ganganloveu/p/4417485.html

结果代码:

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


0 0