【问题标题】:tracing back recursive calls追溯递归调用
【发布时间】:2017-03-22 14:56:55
【问题描述】:

我是递归的新手,并试图了解它是如何工作的,并试图追踪它是如何接近找到答案的。下面编写的代码找出整数数组中搜索数字的最后一个索引,例如@987654321 @ 并且在这个数组中搜索到的数字是 2 。 这个问题的答案是3,因为它是最后一个索引。现在我将尝试编写这段代码是如何做到的。in[] 是输入数组,而 stin 是起始整数和要找到的数字是num

  1. 在 int ans lastINdex(in,stin+1,size,num) 行,该函数被递归调用到它的基本情况,即当它的大小变为 stin==siz 时。然后它的值被返回给调用的函数它。我的问题是这个函数将如何到达递归语句之后的行。请提供此代码的解释。

    int lindex(int in[], int stin, int num){ int size=strlen(in); if(stin == size){ return -1; } int ans = lastIndex(in, stin + 1, num); if(ans != -1){ return ans; }else{ if(in[stin] == num){ return stin; }else{ return -1; } } }

【问题讨论】:

    标签: arrays recursion


    【解决方案1】:

    实现将在递归调用之后通过返回到达该行。如果一个人不熟悉递归,可能需要一些时间来适应它。如果您能够使用调试器,我强烈建议您尝试使用它并检查调用堆栈和局部变量值。但是,递归调用的序列可以扩展如下,使用您的示例,使用伪编码符号,其中插入值。

    1. call lindex({1,2,3,4}, 0, 2):
       int size=strlen(in); // assigns 4
       if(0 == 4){          // condition is false
       }
       int ans = lastIndex({1,2,3,4}, 1, 2); // assigns 3, as we see below
       if(3 != -1){         // condition is true
           return 3;
       }
    
    2. call lindex({1,2,3,4}, 1, 2):
       int size=strlen(in); // assigns 4
       if(1 == 4){          // condition is false
       }
       int ans = lastIndex({1,2,3,4}, 2, 2); // assigns 3, as we see below
       if(3 != -1){         // condition is true
           return 3;
       }
    
    3. call lindex({1,2,3,4}, 2, 2):
       int size=strlen(in); // assigns 4
       if(2 == 4){          // condition is false
       }
       int ans = lastIndex({1,2,3,4}, 3, 2); // assigns 3, as we see below
       if(3 != -1){         // condition is true
           return 3;
       }
    
    4. call lindex({1,2,3,4}, 3, 2):
       int size=strlen(in); // assigns 4
       if(3 == 4){          // condition is false
       }
       int ans = lastIndex({1,2,3,4}, 4, 2); // assigns -1, as we see below
       if(-1 != -1){         // condition is false
       }else{
           if(in[3] == 2){   // condition is true
           return 3;
       }
    
    5. call lindex({1,2,3,4}, 4, 2):
       int size=strlen(in); // assigns 4
       if(4 == 4){          // condition is true
           return -1;
       }
    

    如果我们讨论各个步骤的语义,实现会变得更容易理解。首先,检查起始索引点是否在数组后面,在这种情况下,找不到所需的数字并返回 -1。否则,我们在数组的尾部寻找要找到的数字。如果可以在那里找到,我们返回在递归调用中找到的索引。否则,我们测试当前位置是否与要查找的所需数字相等,因为它不会出现在数组的尾部。总的来说,这会返回搜索到的数字最右边出现的索引(如果它被包含的话)。

    从递归调用返回的“后退”是通过调用堆栈完成的;每个递归调用都有自己的一组局部变量。

    【讨论】:

    • int ans = lastIndex({1,2,3,4}, 1, 2); // assigns 3, as we see below 这个步骤如何返回 3
    • @bogor 调用如何返回 3 在步骤 3 中进行了描述,其中进一步遵循递归。
    猜你喜欢
    • 2013-08-02
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多