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.

思路:

动态规划,设置maxn[i]表示到第i个房子位置,最大收益。

递推关系为maxn[i] = max(maxn[i-2]+nums[i], maxn[i-1]);


C++代码:

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


你可能感兴趣的:(LeetCode,C++)