【问题标题】:Changing the contents of an array in a recursive function在递归函数中更改数组的内容
【发布时间】:2019-08-01 06:46:58
【问题描述】:

我无法理解有关递归和数组的内容。

基本上,该程序所做的是检查可以放置在两个盒子中的物品的最大重量是多少。我知道它远非现在的完美,但这不是重点。

通常一切正常,但是,现在我决定在重量最大时查看每个盒子的内容。为此,我尝试使用 arr1 和 arr2。

我不明白为什么 arr1 和 arr2 得到不同的结果(第一个选项给了我想要的结果,第二个没有)。

这是程序:

#define N 5
int help(int items[N][2], int box1[N], int box2[N], int rules[N][N], 
         int optimal,int current_weight,int item,int arr1[],int arr2[])
{
  if (item == N)
    {
      if(current_weight>optimal) //This is the first option
        {
          memcpy(arr1,box1,sizeof(int)*N);
          memcpy(arr2,box2,sizeof(int)*N);
        }
      return current_weight;
    }
  int k = items[item][1]; int sol;
  for (int i = 0; i <= k; i++)
    {
      for (int j = 0; i+j <= k; j++)
        {
          box1[item] += i; box2[item] += j;
          if (islegal(items, box1, box2, rules))
            {
              sol = help(items, box1, box2, rules, optimal, 
                   current_weight + (i + j)*items[item][0],item+1,arr1,arr2);
              if (sol > optimal)
                {
                  optimal = sol;
                  memcpy(arr1,box1,sizeof(int)*N); //This is the second option
                  memcpy(arr2,box2,sizeof(int)*N);
                }
            }
          box1[item] -= i; box2[item] -= j;
        }
    }
  return optimal;
}

int insert(int items[N][2], int rules[N][N])
{
  int box1[N] = { 0 }; int arr1[N] = { 0 };
  int box2[N] = { 0 }; int arr2[N] = { 0 };
  int optimal = 0;
  int x = help(items, box1, box2, rules,0, 0,0,arr1,arr2);
  print(arr1, N);
  print(arr2, N);
  return x;
}

谁能解释造成这种差异的原因?为什么第一个选项正确而第二个选项不正确?我自己也想不通。

非常感谢。

【问题讨论】:

    标签: c arrays recursion backtracking


    【解决方案1】:

    这不起作用,因为当您传递 box1box2 来帮助时,它们会被 help 变异。从算法中很明显,您希望它们不会发生变异。所以,我们可以这样做:

    int help(int items[N][2], int box1in[N], int box2in[N], int rules[N][N], 
             int optimal,int current_weight,int item,int arr1[],int arr2[])
    {
        int box1[N];
        int box2[N];
        memcpy(box1, box1in, sizeof(int)*N);
        memcpy(box2, box2in, sizeof(int)*N);
    

    您的算法可能仍有问题,但该问题现已消除。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-05
      • 2021-10-10
      • 1970-01-01
      • 2016-01-22
      • 1970-01-01
      • 2020-07-19
      相关资源
      最近更新 更多