标签:动态规划
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];
   }
标签:动态规划
原文地址:http://blog.csdn.net/sinat_24520925/article/details/45071003