0-1揹包問題,是說給定 n 個物體,每個物體都有一定的重量和價值,再給一個能容納最大重量爲 w 的揹包。求從 n 個物體中選出若干個放到揹包中,在所選物體總重量不超過 w 的情況下,所選物體的總價值最大。
注意:所有物體都不可分割。
分析:這個問題可抽象爲給定兩個數組 wt[0..n-1] 和 val[0..n-1],第一個數組表示各物體的重量,第二個數組表示各物體的價值。從 wt 數組中選出若干個元素,它們的總重複不超過 w,而且總價值最大。
這是動態規劃裏的一個經典問題
1.最優子結構性質
在所有的組合中,對任一給定的物體,它要在麼在一個組合裏面,要麼不在這個組合裏面。所以最大價值可這樣選擇:
1)不包括第 n 個物體,只從剩餘的 n-1 個物體中選擇;
2)包括第 n 個物體,剩餘的重量 W-wt[n-1] 要從剩餘的 n-1 個物體中選擇。
如果第 n 個物體重量超過 W,那麼就只能選第一種情況,由此得到下面的遞歸程序
#include<stdio.h>
// A utility function that returns maximum of two integers
int max(int a, int b) { return (a > b)? a : b; }
// Returns the maximum value that can be put in a knapsack of capacity W
int knapSack(int W, int wt[], int val[], int n)
{
// Base Case
if (n == 0 || W == 0)
return 0;
// If weight of the nth item is more than Knapsack capacity W, then
// this item cannot be included in the optimal solution
if (wt[n-