不积跬步,无以至千里;不积小流,无以成江海。——荀子

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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.

题目大意:有一个小偷要去街上的一排房子偷钱,每个房子里面有一定数量的钱,限制条件是你不能同时偷相邻两个房子的钱。现在给定一个非负的整数,表示每个房子里的钱,求在不能同时偷相邻两个房子的条件下,小偷能偷的最多的钱。

分析:设ret[i]表示到达第i个房子时,最大能偷的钱。由于不能偷相邻房子的钱,故只有两种情况,

1)在i-2房子偷钱,i-1房子不偷钱,则此时最大能偷的钱为ret[i-2]+nums[i]

2)在i-2房子不偷钱,i-1房子偷钱,此时最大能偷的钱为ret[i-]

因此,只要比较上述两个情况,选择最大能偷的钱,即为到达当前房子能偷的最大钱。

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

 

posted on 2017-10-01 00:51  hejunlin  阅读(111)  评论(0编辑  收藏  举报