动态规划解决01背包问题

/*
   @param weights: 物品的重量
   @param value:物品的价值
   @param capacity:背包的总容量
*/

int KnapSack_01(vector weights, vector value, int capacity)
{
	int size = weights.size();
	if (size == 0)
		return 0;
	vector dp(capacity + 1, 0);

	for (int i = 0; i <= capacity; i++)
		dp[i] = weights[0] <= i ? value[0] : 0;

	for (int i = 1; i < size; i++)
	{
		for (int j = capacity; j >= weights[i]; j--)
		{
			dp[j] = dp[j] > value[i] + dp[j - weights[i]] ? dp[j] : value[i] + dp[j - weights[i]];
		}
	}
	return dp[capacity];
}

 

你可能感兴趣的:(算法)