【问题标题】:recursion with or without return statement in terminating condition在终止条件中有或没有返回语句的递归
【发布时间】:2014-02-25 00:09:33
【问题描述】:

请解释一下 return 语句是如何对 trie 进行简单递归解析的

案例一:

if (true) push &stack; //push path result onto a stack
else{
   if (terminating condition true) return;
   else {
      condition 1 recursion to next node
      condition 2 recursions to next node
      ...
      condition n recursion to next node
   }
   recursion to next path;
}

案例 B:

if (true) {
   push &stack; //push path result onto a stack
   return;
}else{
   if (terminating condition true) return;
   else{
      condition 1 recursion to next node
      condition 2 recursion to next node
      ...
      condition n recursion to next node
   }
   recursion to next path;
}

案例 A 对我来说效果很好。但是,我不明白将结果推送到堆栈后会发生什么。 “它”如何知道终止这些路径?

【问题讨论】:

  • 那么你知道递归fn的工作原理吗?
  • @555k 我不确定你所说的“知道递归 fn 的工作原理”是什么意思

标签: c++ recursion trie


【解决方案1】:

对于返回类型为 void 的函数,return 语句不是绝对必要的。如果在没有遇到 return 语句的情况下到达此类函数的末尾,则将控制权传递给调用者,就像遇到没有表达式的 return 语句一样。换句话说,隐式返回发生在最后一条语句完成时,控制权自动返回到调用函数。无论如何,您不需要为另一行代码付费,添加 return 语句是一个好习惯。
但请注意,对于使用非 void 返回类型声明的函数,它是必需的。它有时可以在没有返回语句的情况下工作,例如,这个:Confused about the function return value。但这是未定义行为的结果。

【讨论】:

    【解决方案2】:

    案例 A 有效,因为结果被推送到堆栈或向量,或使用的任何结构,然后终止该特定路径。如果有返回,它会启动堆栈的解析并退回到之前的迭代。因此,在情况 B 中,只会找到一个结果。

    【讨论】:

      猜你喜欢
      • 2011-12-08
      • 2018-07-21
      • 2015-12-22
      • 1970-01-01
      • 2010-10-30
      • 2018-12-27
      • 1970-01-01
      • 2023-01-01
      • 2014-02-03
      相关资源
      最近更新 更多