House Robber

来源:互联网 发布:银行大数据精准营销 编辑:程序博客网 时间:2024/06/05 08:52
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.

思路:题目的意思是有一个强盗沿街去进行抢劫,每一家的房子中有一定数额的money,不能连续抢劫两家紧挨着的,求这个强盗最大的可以抢劫到的现金数。

考虑在一个位置dp[i]处可以获得最大值的可能值

(1)dp[i]=dp[i-1]  对应的是不抢当前房子,抢了前一家的最大值

(2)dp[i]=dp[i-2]+nums[i]  抢了前一家的前一家,那么由于不相邻,当前的这一家也是可以抢的

因此在一个位置i的最大值dp[i]=max(dp[i-1],dp[i-2]+nums[i])。

另外,需要判断下nums数组的起始个数的一些特殊情况即可

代码如下:

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


0 0
原创粉丝点击