#include<stdio.h>#define N 4 // 物品数量#define W 5 // 背包容量typedefstruct {int weight;
int value;
} Item;
intmax(int a, int b){
return (a > b) ? a : b;
}
intknapsack(Item items[], int n, int capacity, int current){
if (current == n || capacity == 0)
return0;
if (items[current].weight > capacity)
return knapsack(items, n, capacity, current + 1);
// 不选择当前物品int withoutCurrent = knapsack(items, n, capacity, current + 1);
// 选择当前物品int withCurrent = items[current].value +
knapsack(items, n, capacity - items[current].weight, current + 1);
return max(withoutCurrent, withCurrent);
}
intmain(){
Item items[N] = {{2, 12}, {1, 10}, {3, 20}, {2, 15}};
int totalValue = knapsack(items, N, W, 0);
printf("%d\n", totalValue);
return0;
}