I have the following solution for the knapsack problem:(wt[] is the weights array, val[] is the values array, n is the arrays size, index is the current item that we are trying (for the recursion) and arr is an array that represents weather or not item i was included in the solution.
int knapSack(int W, int wt[], int val[], int n, int index, int arr[])
{
if (n == index || W == 0)
return 0;
if (wt[index] > W)
return knapSack(W, wt, val, n, index+1 );
int with=val[index]+knapSack(W-wt[index], wt, val, n, index+1);
int without=knapSack(W, wt, val, n, index+1);
if(with>without){
arr[index]=1;
return with;
}
else{
arr[index]=0;
return without;
}
}
I am trying to print, in this recursive solution the items that are chosen, by setting the indexes of the taken ones in an array (res) to 1.
As I understand, if with>without
, it means that I am choosing the current item, or item #index. So why is this not returning a right value?
I am using the recursive algorithm for a reason, I know using the memoization version can be easier here.
Example:
Weights: 5 6 7 10 11
Values: 2 4 5 6 9
W=25
Will return 5 ones in array res. When solution is 18 with items 2,3,5 (starting from index 1).