House Robber

题目来源:Leetcode Algorithm ProblemSet 198

题目描述: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.

Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.

[cpp]  view plain  copy
  1. class Solution {  
  2. public:  
  3.     int rob(vector<int>& nums) {  
  4.     }  
  5. };  

解题思路:这道题的意思是在一个数组nums中,对于每个i,nums[i]和nums[i+1]最多只能选择一个,求能选出的最大和。这就涉及到了动态规划。如下代码,a[i]代表当前数nums[i]没有选中时前i+1个数的最大和,b[i]代表当前数nums[i]选中时前i+1个数的最大和。
对于每个i>0,均有:
    a[i]:当前数没有选中,则前一个数nums[i-1]可选可不选,a[i] = max(a[i-1], b[i-1])
    b[i]:当前数选中,则前一个数nums[i-1]不可选,b[i] = a[i-1]+nums[i]
最后再比较当a[n-1],b[n-1]的大小,取最大值,即含有n个数的数组的前n个数的最大和。
上面描述的是下面我注释掉的代码,新增加的代码是在注释的代码基础上进行的小修改,可以少用两个数组,节省空间。
时间复杂度为O(n)。
题解代码:
[cpp]  view plain  copy
  1. class Solution {  
  2. public:  
  3.     int rob(vector<int>& nums) {  
  4.         int size = nums.size();  
  5.         if (size == 0) {  
  6.             return 0;  
  7.         }  
  8.         /*int* a = new int[size]; 
  9.         int* b = new int[size]; 
  10.         a[0] = 0; 
  11.         b[0] = nums[0]; 
  12.         for (int i = 1; i < size; i++) { 
  13.             b[i] = a[i-1]+nums[i]; 
  14.             a[i] = max(a[i-1], b[i-1]); 
  15.         } 
  16.         return max(a[size-1], b[size-1]);*/  
  17.         int a = 0, b = nums[0];  
  18.         for (int i = 1; i < size; i++) {  
  19.             int tb = b, ta = a;  
  20.             b = ta+nums[i];  
  21.             a = max(ta, tb);  
  22.         }  
  23.         return max(a, b);  
  24.     }  
  25. };  

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值