I am trying to solve the 0/1 Knapsack problem on GeeksforGeeks and it requires me to complete the funtion
int knapSack(int W, int wt[], int val[], int n)
Now I want to do this with recursion + memoization. But to that I need to define and initialise a DP matrix for every test case. It looks like this.
int dp[1001][1001];
memset(dp,-1,sizeof(dp));
Now What I can think of is define the matrix globally and using memset inside function, but the problem arises is that memset would reset the matrix on every recursive call. Is there a way to get around it? or do I just have to do the tabulation method instead?
Avoid global variable.
Split your method:
int knapSackRec(int (&dp)[1001][1001], int W, int wt[], int val[], int n)
{
// ...
}
int knapSack(int W, int wt[], int val[], int n)
{
int dp[1001][1001];
memset(dp, -1, sizeof (dp));
return knapSackRec(dp, W, wt, val, n);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.