Leetcode刷题总结:198. 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.

输入是非负整数表示每个房子的money,求不引发报警的最大money和

解题:

动态规划问题:

输入是money, 递推公式为:

maxMoney[n] = max(maxMoney[n-1] ,maxMoney[n-2]+money[n])

上代码:

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

 

posted @ 2017-08-27 17:55  糯米团子syj  阅读(107)  评论(0编辑  收藏  举报