递归 - 什么时候会使用它,什么时候不会使用它
递归——什么时候会使用它,什么时候不会使用它?
Recursion - when would you use it and when wouldn't you use it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
递归——什么时候会使用它,什么时候不会使用它?
Recursion - when would you use it and when wouldn't you use it?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(6)
我使用 递归< /a> 每当我遇到问题时 需要递归。
I use recursion whenever I encounter a problem that requires recursion.
一般来说,如果您可以使用 树 数据结构来概念化问题,那么您可以使用递归来导航树。
Generally, if you can conceptualize the problem with a tree data structure then you can use recursion to navigate the tree.
非常依赖语言。对于像 Ruby 这样没有很好的尾部调用优化的语言要非常小心。真正的函数式语言可以更好地处理递归。在开始过度依赖记忆化之前,请确保您了解它。我真正使用它的是当我知道输入和输出的完整范围时。如果我知道我永远不会深入 100 个级别,那么我会使用它(至少在 Ruby 中),否则我会找到不同的模式。我希望递归更快,因为我经常找到一个我喜欢的非常简洁的两行解决方案,但它不能稳定或快速地执行,所以我必须替换它。
Very language dependent. Be very careful with languages like Ruby that don't have very good tail call optimization. True functional languages handle recursion better. Make sure you know about memoization before you start to rely on it too much. Where I really use it is when I know the full bounds of the inputs and outputs. If I know I won't ever, ever, go 100 levels deep then I'll use it (in Ruby, at least), otherwise I find a different pattern. I wish recursion was faster, because so often I find a really neat 2 line solution that I love, but that doesn't preform stably or quickly so I'll have to replace it.
当它使问题变得更容易并且我有大量堆栈内存(如果堆栈很大)时,我会使用它。
如果堆栈内存非常宝贵,我不会使用它(因此调用堆栈不会变得太大并导致堆栈溢出和应用程序失败)。
I would use it when it made a problem easier and I had a large amount of stack memory (in case of a large stack).
I wouldn't use it if stack memory was at a premium (so the call stack doesn't grow too large and cause the stack to overflow and your application to fail).
如果您知道您的语言/环境对调用堆栈深度有限制,我不会使用它。我记得使用 Lotus Notes 的早期版本,它的深度限制为 16 级,这使得几乎不可能使用任何递归。
I would NOT use it if you know your language / environment has a limitation on the calling stack depth. I remember working with an early version of Lotus Notes which had a limit of something like 16 levels deep - which would make almost any use of recursion impossible.
当且仅当它显然是正确的解决方案并且没有其他方法可能是正确的时,我才会使用它。
也许对于阶乘函数,尽管可能不是。 请尝试斐波那数列。
如果您想要一个例子来说明看似可以通过递归解决的问题如何很快变得非常丑陋,
I would use it if, and only if, it was obviously the correct solution and no other method could possibly be correct.
Perhaps for a factorial function, although probably not. Try the Fibonnaci sequence
if you want an example of how something apparently solvable by recursion can grow very ugly very quickly.