0/1 knapsack problem. Learning Dp

I have started learning dp from youtube from aditya verma channel which is pretty good and i went to solve the question ..my code is either giving tle or i am getting wrong answer..I have tried to ask to a lot of people on different site but could not get help..Hopefully someone here can answer ..i am pasting my memoized code here and please tell where is the error or what wrong i am doing
class Solution
{
public:

int t[1002][1002]; //The constraint for N and T was 1<=N,T<=1000
int ans(int W, int wt[], int val[], int n)
{
if(n==0||W==0)
return 0;//base case

   else
   if (t[n][W]!=-1)
   return t[n][W]; //if already calculated
   else
   {
       
   if(wt[n-1]<=W)
   {
        return t[n][W]= max(val[n-1]+knapSack(W-wt[n-1],wt,val,n-1),knapSack(W,wt,val,n-1));
   }

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

}
}

int knapSack(int W, int wt[], int val[], int n) 
{  
    memset(t,-1,sizeof(t));
   
   
   return ans(W, wt, val, n);
   
   }
   
   

};

Comments (0)