您的位置:首页 > 其它

LeetCode OJ:House Robber(住宅窃贼)

2015-10-20 10:10 197 查看
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]较大,代码如下:

class Solution {
public:
int rob(vector<int>& nums) {
int sz = nums.size();
vector<int> maxRet = nums;
if(sz == 0) return 0;
if(sz == 1) return nums[0];
if(sz == 2) return max(nums[0], nums[1]);
int i;
maxRet[0] = nums[0];
maxRet[1] = max(nums[0], nums[1]);
for(i = 2; i < sz; ++i){
maxRet[i] = max(maxRet[i - 2] + nums[i], maxRet[i - 1]);
}
return maxRet[i - 1];
}
};


java版本的代码和上面一样,如下所示:

public class Solution {
public int rob(int[] nums) {
int sz = nums.length;
if(sz == 0)
return 0;
if(sz == 1)
return nums[0];
if(sz == 2)
return Math.max(nums[0], nums[1]);
int [] ret = new int [sz];
ret[0] = nums[0];
ret[1] = Math.max(nums[0], nums[1]);
for(int i = 2; i < sz; ++i){
ret[i] = Math.max(ret[i-2] + nums[i], ret[i-1]);
}
return ret[sz-1];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: