LeetCode 198. House Robber

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

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

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

 

这个题目是典型的动态规划,第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的主要内容,如果未能解决你的问题,请参考以下文章

leetCode 198. House Robber | 动态规划

LeetCode 198. House Robber

Leetcode 198 House Robber

[leetcode-198-House Robber]

leetcode 198. House Robber

[LeetCode] 198. House Robber