House Robber

来源:互联网 发布:签名设计特效软件 编辑:程序博客网 时间:2024/06/06 10:50

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.

动态规划问题:

到第i个房子的最大收益为:maxValue[i] = max(maxValue[i-2]+nums[i],maxValue[i-1]);

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


0 0
原创粉丝点击