I am trying to make a problem with a backpack, and this is a recursive solution that I came across. Can it be done better? I think I need to add memoization, checking if I have reached this state before. Is it right that I need to add state for state[c_w][i]?
I intentionally did not use dynamic programming, as I know the repeat relationships for this, but wanted to get the right recursion.
#include <stdio.h>
int memoize[1000][1000];
int max(int a, int b)
{
return a>b?a:b;
}
int max_profit_func(int *val, int *wt, int W, int c_w, int i, int size)
{
int max_profit = 0;
int j;
if (i >= size)
return 0;
if (memoize[c_w][i] != -1)
return memoize[c_w][i];
for(j=i;j<size;j++) {
int profit = 0;
if (c_w+wt[j] <= W)
profit = val[j] + max_profit_func(val, wt, W, c_w+wt[j], j+1, size);
max_profit = max(max_profit, profit);
}
memoize[c_w][i] = max_profit;
return max_profit;
}
int main(void) {
int val[] = {3, 7, 2, 9};
int wt[] = {2, 3, 4, 5};
int W = 5;
memset(memoize, -1, sizeof(int)*1000*1000);
printf("%d\n", max_profit_func(val, wt, W, 0, 0, sizeof(wt)/sizeof(wt[0])));
return 0;
}
source
share