[LeetCode] House Robber

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,C++)