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

LeetCode OJ:House Robber(住宅窃贼)

时间:2015-10-20 10:23:11      阅读:162      评论: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.

简单点讲,题目的意思就是,一连串数字,不能去相邻的值,那么怎么样才能取到其中的最大值。DP,表达式为:ret[i] = max(ret[i - 1], ret[i - 2] + nums[i]);

一开始想还有一种可能就是ret[i - 1]可能就是ret[i - 2],但是这里不影响,因为还是ret[i - 2] + num[i]较大,代码如下:

 1 class Solution {
 2 public:
 3     int rob(vector<int>& nums) {
 4         int sz = nums.size();
 5         vector<int> maxRet = nums;
 6         if(sz == 0) return 0;
 7         if(sz == 1) return nums[0];
 8         if(sz == 2) return max(nums[0], nums[1]);
 9         int i;
10         maxRet[0] = nums[0];
11         maxRet[1] = max(nums[0], nums[1]);
12         for(i = 2; i < sz; ++i){
13             maxRet[i] = max(maxRet[i - 2] + nums[i], maxRet[i - 1]);
14         }
15         return maxRet[i - 1];
16     }
17 };

 

LeetCode OJ:House Robber(住宅窃贼)

标签:

原文地址:http://www.cnblogs.com/-wang-cheng/p/4893971.html

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