首页 > 解决方案 > 递归:如何保持 for 循环中不断变化的变量在递归期间不发生变化?

问题描述

我在递归函数中有一个 for 循环。每次 for 循环完成时,我的代码中的索引 i 都会更改,但是当递归开始时它会重置。是否可以通过另一个变量或类似的任何东西保存值?我需要一个变量来保持第一个递归步骤的“i”值(或者更确切地说是在任何递归开始之前我拥有的“i”值)。我的实际代码似乎相当复杂,所以我只是粘贴了一个示例代码来解释我的问题。

我尝试过使用其他变量,还有全局变量。不幸的是,每当递归发生时它们也会改变,因为我需要以某种方式将“i”值保存给它们。

   int array[2][10];
   void function(){
      int x = 1;
      for (int i = 0; i < 10; i++){
         //Something happens here... (The base cases are in here)
         for (int j = 0; j < 10; j++){
            //Something happens here...(More base cases are in here)
            array[0][x] += i; //When function() starts, i is 0. I need it to 
                              //remain 0, while it
                              //runs through all the recursion steps (limited 
                              //by a recursion counter).
                              //After the recursion returns to the first level, 
                              //the for loop will continue.
                              //'i' will be 1 and then I need this value to 
                              //stay the same throughout all the
                              //recursion steps once again. How do I do that?
            //Recursion
            function();
         }
      }
   }

我希望 'i' 保持不变,但每次递归重新启动 for 循环时都会重置它。

标签: crecursion

解决方案


听起来您可能想将i循环移出function,然后将其传入。

例如,如果你有类似的东西:

void someOtherFunction()
{
    function();
}
void function(){
  int x = 1;
  for (int i = 0; i < 10; i++){
     //Something happens here...
     for (int j = 0; j < 10; j++){
        //Something happens here...
        array[0][x] += i;
        //Recursion
        function();
     }
  }
}

您可以将其更改为:

void someOtherFunction()
{
    for (int i=0; i<10; ++i)
        function(i);
}
void function(int i){
  int x = 1;
 //Something happens here...
 for (int j = 0; j < 10; j++){
    //Something happens here...
    array[0][x] += i; 
    //Recursion
    function(i);
  }
}

i在这种情况下,可能有一个更好、更具描述性的名称。


推荐阅读