您的位置:首页 > 编程语言 > C语言/C++

House Robber[leetcode]题解 c++

2015-06-21 21:24 537 查看
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.

Credits:

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

题目大意:在一串正整数串当中取一组整数串,且整数串中的数两两之间不相邻,求得许多串方案当中和最大的串,输出和。

 一开始简单以为只是一个判断奇数偶数然后对于一些特殊情况特判一下的情况,后来才发现想当然了,改用动态规划的办法但是也就是递推了一下。

对于数组长度小等于3的特殊处理,数组长度大于3的采用的状态转移方程为:

dp[i] = max(dp[i-2],dp[i-3])+nums[i];

思路:就是以局部最大推导整体最大,需要判断的只是与第i-2的数相加,还是与第i-3的数相加,而第i-4自然不用考虑。

实现c++代码:

#include<cstdio>
#include<cstring>
#include<string>
#include<cstdlib>
#include<map>
#include<vector>
#include<iostream>
using namespace std;
class Solution {
public:
int rob(vector<int>& nums) {
if(nums.size() == 0)
{
return 0;
}
if(nums.size() == 1)
{
return nums[0];
}
if(nums.size() == 2)
{
return max(nums[0],nums[1]);
}
if(nums.size() == 3)
{
return max(nums[0]+nums[2],nums[1]);
}
int dp[nums.size()];
dp[0] = nums[0];
dp[1] = nums[1];
dp[2] = nums[0]+nums[2];
for(int i = 3;i<nums.size();i++)
{
dp[i] = max(dp[i-2],dp[i-3]) + nums[i];
}
//注意数组边界问题
return max(dp[nums.size()-3],max(dp[nums.size()-1],dp[nums.size()-2]));
}
};
int main()
{
vector<int> v;
for(int i = 0;i<10;i++)
{
v.push_back(i);
}
Solution s;
cout << s.rob(v)<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息