码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] House Robber

时间:2015-04-07 15:43:40      阅读:340      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   

House Robber

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.

解题思路:

动态规划。d[i]=max(d[i-2]+num[i], d[i-1]); 这两种情况分别代表倒数第2间房不偷,倒数第二间房偷的最大钱数。注意边界的情况。下面是代码:

class Solution {
public:
    int rob(vector<int> &num) {
        int len=num.size();
        if(len==0){
            return 0;
        }
        if(len==1){
            return num[0];
        }
        if(len==2){
            return max(num[0], num[1]);
        }
        int* d=new int[len];
        
        d[0]=num[0];
        d[1]=max(num[0], num[1]);
        for(int i=2; i<len; i++){
            d[i]=max(d[i-2]+num[i], d[i-1]);
        }
        
        int result=d[len-1];
        delete[] d;
        return result;
    }
    
private:
    int max(int a, int b){
        return a>b?a:b;
    }
};

[LeetCode] House Robber

标签:c++   leetcode   

原文地址:http://blog.csdn.net/kangrydotnet/article/details/44919847

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!