[week 11][Leetcode][Dynamic Programming] House Robber

来源:互联网 发布:剑三男神脸数据 花哥 编辑:程序博客网 时间:2024/05/22 13:01
  • Question:

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 andit 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 tonightwithout alerting the police.


  • Analysis:
这是一道关于动态规划的题目,需要求出小偷一个晚上最多可以偷到的金钱数目。举个例子将会很容易看出其中的关系,比如一条街上每户人家的金额为[6,12,8,9,10,4,3]。首先从第一,二户人家中选择一户进行偷盗,所以金额不变,到第三户人家时,此时小偷可以偷到的最大金额为:6,12,14,9,10,4,3;到第四户人家时,小偷只需要考虑排在他之前的第二和第三户人家的金额,此时他偷盗第四户时可以偷盗的最大金额为:6,12,14,21,10,4,3;以此类推,到第五户人家时:6,12,14,21,24,4,3;第六户:6,12,14,21,24,25,3;最后一户:6,12,14,21,24,25,27。所以一个晚上他可以偷盗且不会引起报警的金额为27。由这个例子我们可以明显看出其状态转移方程为:F[n] = max{F[n-2],F[n-3]} + F[n]。代码如下所示。
  • Code:
class Solution {public:    int rob(vector<int>& nums) {        const int n = nums.size();        int result = 0;        if (n==0)            return 0;                if (n == 1)            return nums[0];                if (n == 2)        {            result = max(nums[0],nums[1]);            return result;        }                if (n == 3)        {            result = max(nums[1],(nums[0]+nums[2]));            return result;        }                if (n >= 4)        {            nums[2] += nums[0];            result = nums[2];            for (int i=3;i<n;i++)            {                nums[i] = max(nums[i-2],nums[i-3])+nums[i];                result = max(result,nums[i]);            }            return result;        }            }};