01背包问题动态规划解法

二维数组dp

#include
#include
using namespace std;

vectorweight = { 1,3,4 };
vectorvalue = { 15,20,30 };
int bagWeight = 4;
vector>dp(weight.size() + 5, vector(bagWeight + 5, 0));
//dp[i][j]表示从0-i个物品中选取最大容量为j的背包所容纳的最大价值

void printDp(vector>& dp)
{
	for (int i = 0; i < weight.size(); i++)
	{
		for (int j = 0; j <= bagWeight; j++)
		{
			cout << dp[i][j] << " ";
		}
		cout << endl;
	}
}
int main()
{
	int i, j;
	//初始化
	for (j = weight[0]; j <= bagWeight; j++)
	{
		dp[0][j] = value[0];
	}

	cout << "开始dp前" << endl;
	printDp(dp);

	//开始dp
	for (i = 1; i < weight.size(); i++)
	{
		for (j = 0; j <= bagWeight; j++)
		{
			if (j < weight[i])
			{
				dp[i][j] = dp[i - 1][j];
			}
			else
			{
				dp[i][j] = max(dp[i - 1][j], dp[i][j - weight[i]] + value[i]);
			}
		}
	}

	cout << "完成dp后" << endl;
	printDp(dp);
	cout << "最大价值为:" << dp[weight.size() - 1][bagWeight] << endl;
	return 0;
}

一维数组

#include
#include
using namespace std;

vectorweight = { 1,3,4 };
vectorvalue = { 15,20,30 };
int bagWeight = 4;
vectordp(bagWeight+5, 0);
//dp[j]表示背包最大容量为j的所放物品的最大价值

void printDp(vector& dp)
{
	for (int j = 0; j <= bagWeight; j++)
	{
		cout << dp[j] << " ";
	}
}
int main()
{
	int i, j;
	//开始dp
	for (i = 0; i < weight.size(); i++)
	{
		for (j = bagWeight; j >= weight[i]; j--)
		{
			dp[j] = max(dp[j], dp[j - weight[i]] + value[i]);
		}
		printDp(dp);
		cout << endl;
	}
	cout << "最大价值为:" << dp[bagWeight] << endl;
	return 0;
}

你可能感兴趣的:(C++学习基础学习,算法学习,动态规划,算法)