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

LeetCode 198. House Robber

时间:2016-04-05 07:06:00      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

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.

题目:你是一个非常牛逼的强盗,计划抢一条街。每个屋子里面都存有一定数量的钱,唯一制约你抢钱的原因是:相邻的屋子的安全系统是相连的,如果在同一个晚上,两个相邻的屋子被闯入了,安全系统会自动的报警。

求解你不惊动警察,能抢多少钱

 

这个题目是典型的动态规划,第i次决定是否抢钱,要看是前i-2个屋子里面能抢到的最多的钱与第i个屋子的钱之和是否大于前i-1个屋子里能抢到的最多的钱!

 

class Solution {
public:
    //辅助函数,用来取出较大的数
    int max(int a, int b)
    {
        return a > b ? a : b;
}
    int rob(vector<int>& nums) {
        //建立一个长度为n的向量,第i-1位用来保存前i家可以抢到的最多的钱
        vector<int> money(nums.size(), 0);
        if (0 == nums.size())return 0;
        if (1 == nums.size())return nums[0];
        else
        {
            money[0] = nums[0];
            money[1] = max(nums[0], nums[1]);
            for (unsigned int i = 2;i < nums.size();++i)
                //得出前i家可以抢到的最多的钱
                money[i] = max(nums[i] + money[i - 2], money[i - 1]);
        }
        return money[nums.size() - 1];
    }
};

 

LeetCode 198. House Robber

标签:

原文地址:http://www.cnblogs.com/csudanli/p/5353610.html

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