// Naive method
int MaxValue( vector<int>value, vector<int>weight, int MaxWeight, int size ) {
if ( size == 0 ) return 0;
if ( weight[size - 1] > MaxWeight ) {
return MaxValue( value, weight, MaxWeight, size - 1 );
}
return max(
value[size - 1] + MaxValue( value, weight, MaxWeight - weight[size - 1], size - 1 ),
MaxValue( value, weight, MaxWeight, size - 1 )
);
}
int OneZero_Knapsack_Naive( vector<int>value, vector<int>weight, int MaxWeight ) {
return MaxValue( value, weight, MaxWeight, value.size() );
}
/*
Dynamic Programming approach for 0-1 knapscak
Not work when value or weight include float items !!
*/
#define index(a,b) ((MaxWeight+1)*(a) + (b))
int OneZero_Knapsack_DP( vector<int>value, vector<int>weight, int MaxWeight ) {
int size = value.size();
vector<int> totalValue;
totalValue.resize( ( MaxWeight + 1 )*( size + 1 ) ); // Use 1-D array to represent matrix tatalValue[size+1][MaxWeight+1]
for ( int i = 0; i <= size; i++ ) {
for ( int j = 0; j <= MaxWeight; j++ ) {
if ( i == 0 || j == 0 )
totalValue[index( i, j )] = 0;
else if ( j >= weight[i - 1] ) {
totalValue[index( i, j )] = max(
totalValue[index( i - 1, j )], // Not include the ith item for max weight j
value[i - 1] + totalValue[index( i - 1, j - weight[i - 1] )] ); // Include the ith item
}
else
// Exceed the max weight, so cannot include the ith item
totalValue[index( i, j )] = totalValue[index( i - 1, j )];
}
}
return totalValue[index( size, MaxWeight )];
}