Can my recursive solution for Knapsack be improved?

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;
}

/* c_w-current weight of the container */ 
int max_profit_func(int *val, int *wt, int W, int c_w, int i, int size)
{
        int max_profit = 0;
        int j;

        /* if the current item is beyond the range then we have 0 profit*/
        if (i >= size)
                return 0;
        if (memoize[c_w][i] != -1)
                return memoize[c_w][i];
        /* get the profit with this index and if the profit is more than previous
         * than store it */
        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;
}
+4
source share
1 answer

You're right. As long as your function solves the problem, it recounts the same things over and over.

2- , , (c_w, i) . memoization ( ): http://en.wikipedia.org/wiki/Memoization

+2

All Articles