递归与循环 [英] Recursion vs loops
问题描述
我面临一个问题,即递归和使用循环似乎都是自然的解决方案.对于这种情况,是否有约定或首选方法"? (显然,它不像下面这样简单)
I'm facing a problem where both recursion and using a loop seem like natural solutions. Is there a convention or "preferred method" for cases like this? (Obviously it is not quite as simple as below)
Item Search(string desired, Scope scope) {
foreach(Item item in scope.items)
if(item.name == desired)
return item;
return scope.Parent ? Search(desired, scope.Parent) : null;
}
循环
Item Search(string desired, Scope scope) {
for(Scope cur = scope; cur != null; cur = cur.Parent)
foreach(Item item in cur.items)
if(item.name == desired)
return item;
return null;
}
推荐答案
在以下情况下,我赞成递归解决方案:
I favor recursive solutions when:
-
递归的实现比迭代解决方案简单得多,通常是因为它以迭代方法无法实现的方式利用了问题的结构方面
The implementation of the recursion is much simpler than the iterative solution, usually because it exploits a structural aspect of the problem in a way that the iterative approach cannot
可以肯定地说,假设我们正在谈论以这种方式实现递归的语言,则递归的深度不会导致堆栈溢出
I can be reasonably assured that the depth of the recursion will not cause a stack overflow, assuming we're talking about a language that implements recursion this way
条件1在这里似乎并非如此.迭代解决方案的复杂度大致相同,因此我坚持使用迭代路线.
Condition 1 doesn't seem to be the case here. The iterative solution is about the same level of complexity, so I'd stick with the iterative route.
这篇关于递归与循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!