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

House Robber

时间:2015-04-16 10:22:38      阅读:141      评论: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.

题目大意:

你是一名专业强盗,计划沿着一条街打家劫舍。每间房屋都储存有一定数量的金钱,唯一能阻止你打劫的约束条件就是:由于房屋之间有安全系统相连,如果同一个晚上有两间相邻的房屋被闯入,它们就会自动联络警察,因此不可以打劫相邻的房屋。

给定一列非负整数,代表每间房屋的金钱数,计算出在不惊动警察的前提下一晚上最多可以打劫到的金钱数。

解题思路:

动态规划(Dynamic Programming)

状态转移方程:

r[j] = max(r[j - 1], r[j - 2] + num[j - 1])

其中, num[j - 1]指的是第j间房间的金钱数量,r[j]表示打劫到第j间房屋时累计取得的金钱最大值。

为了使程序一般性,在第一间房间前加两个房间,即n+2个房间,并且房间中的金钱数目为0;

具体代码如下:

#include<iostream>
#include<vector>
using namespace std;
int rob(vector<int> &num);
void main()
{
	int a[6]={1,3,4,1,2,6};
	vector<int> b(a,a+6);
	int res=rob(b);
	cout<<res;
}
int rob(vector<int> &num) {
	if(num.size()==0) return 0;
	int n=num.size();
	vector<int> r(n+2,0);
	vector<int> num_new(2,0);
	num_new.insert(num_new.end(),num.begin(),num.end());//将加入的金钱数为0的两个家庭和原有的n个家庭合并
	for (int j=2;j<n+2;j++)
	{
		int q=r[j-1];
		if (q<r[j-2]+num_new[j])
		{
			q=r[j-2]+num_new[j];
		}
		r[j]=q;
	}
	cout<<endl;
	for (int i=0;i<n+2;i++)
	{
		cout<<r[i]<<" ";
	}
	return r[n+2-1];
   }





House Robber

标签:动态规划

原文地址:http://blog.csdn.net/sinat_24520925/article/details/45071003

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