简体   繁体   English

如何在递归 function 中只定义和初始化一次变量?

[英]How to define and initialize a variable only once in a recursive function?

I am trying to solve the 0/1 Knapsack problem on GeeksforGeeks and it requires me to complete the funtion我正在尝试解决 GeeksforGeeks 上的 0/1 背包问题,它需要我完成功能

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.但是为此我需要为每个测试用例定义和初始化一个 DP 矩阵。 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.现在我能想到的是全局定义矩阵并在 function 中使用 memset,但问题是 memset 会在每次递归调用时重置矩阵。 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM