This code involves the concept of memory functions. Here we solve the subproblems which are needed unlike the below example F is a 2D array with -1s filled up
(i,wt,val,j)
| 2 | Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. |
| 3 | """ |
| 4 | def MF_knapsack(i,wt,val,j): |
| 5 | ''' |
| 6 | This code involves the concept of memory functions. Here we solve the subproblems which are needed |
| 7 | unlike the below example |
| 8 | F is a 2D array with -1s filled up |
| 9 | ''' |
| 10 | global F # a global dp table for knapsack |
| 11 | if F[i][j] < 0: |
| 12 | if j < wt[i - 1]: |
| 13 | val = MF_knapsack(i - 1,wt,val,j) |
| 14 | else: |
| 15 | val = max(MF_knapsack(i - 1,wt,val,j),MF_knapsack(i - 1,wt,val,j - wt[i - 1]) + val[i - 1]) |
| 16 | F[i][j] = val |
| 17 | return F[i][j] |
| 18 | |
| 19 | def knapsack(W, wt, val, n): |
| 20 | dp = [[0 for i in range(W+1)]for j in range(n+1)] |