mercredi 23 juin 2021

How to use memorization in recursion to solve 0-1 Knapsack problem without Runtime Error for larger inputs in c ++?

For small inputs the code is running fine! .For bigger inputs I am getting an "Time Limit Exceeded" error can some one explain the reason .I have used (recursion +memorization)

Link to the problem:https://practice.geeksforgeeks.org/problems/0-1-knapsack-problem0945/1#

Here is the code :

int a[10005][10005]; // I have declared this globally.

int knapSack(int W, int wt[], int val[], int n) 
{ 
     memset(a,-1,sizeof(a));

     if (n == 0 || W == 0)
     {
     return 0;
     }

     if(a[n][W]!=-1)
     {
     return a[n][W];
     }

     if (wt[n - 1] > W)
     {
     a[n][W]=knapSack(W, wt, val, n - 1);  
     return a[n][W];
    }

    if(wt[n - 1] <= W)
    {
    a[n][W]= max(val[n - 1]+ knapSack(W - wt[n - 1],wt, val, n - 1),knapSack(W, wt, val, n - 1));
    return a[n][W];
    }
}

For smaller Input's:

For Input:

3 // n=no.of inputs

4 //W capacity of the bag

1 2 3 //val[ ]

4 5 1 //wt[ ]

your output is: 3

For larger Input's:

"Time Limit Exceeded"

Aucun commentaire:

Enregistrer un commentaire