java 递归是如何工作的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12885105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does recursion work?
提问by Lexy Feito
Please explain how recursion works, in the simplest way you can.
请以最简单的方式解释递归的工作原理。
采纳答案by Rohit Jain
Here's a simple example of recursive method: -
这是递归方法的一个简单示例:-
public int recur(int count) {
if (count < 10) {
return count + recur(count++);
}
return count;
}
System.out.println(recur(0)); // Invoke first time
回答by Johan Sj?berg
As been pointed out, recursion is when a function calls itself. Here illustrated using factorial
, where factorial(5)
mathematically evalutates to values 5 * 4 * 3 * 2 * 1
.
如前所述,递归是指函数调用自身。此处说明使用factorial
,其中factorial(5)
数学计算值5 * 4 * 3 * 2 * 1
。
public int factorial(int x) {
if (x == 1) return 1;
else return x * factorial (x - 1);
}
// Try routine
factorial(3);
Which evaluates as
其中评估为
factorial(1) = 1 = 1
factorial(2) = 2 * factoral(1) = 2 * 1
factorial(3) = 3 * (2 * factorial(2) * (factorial(1)) = 3 * 2 * 1
...
回答by Joachim Isaksson
Usually, it's a function that calculates one result itself, and calls itself to get the rest of the results.
通常,它是一个函数,它自己计算一个结果,并调用自己来获取其余的结果。
For example, to get all positive numbers less or equal to 3, the function says, "One result is 3, and the rest of the results are all positive numbers less or equal to 2. Let's call myself with 2 and add that result to the one I calculated."
例如,要获取所有小于或等于 3 的正数,该函数会说,“一个结果是 3,其余结果都是小于或等于 2 的正数。让我们用 2 调用自己,然后将该结果添加到我计算的那个。”
Of course, recursive functions need to be careful to have an "end condition" or they will never return a result. In the case of this example, the end condition would be when the function is called with 0, it should just return 0.
当然,递归函数需要小心有一个“结束条件”,否则它们将永远不会返回结果。在这个例子中,结束条件是当函数以 0 调用时,它应该只返回 0。
回答by Max Woolf
Recursion is a method which calls itself from within itself.
递归是一种从自身内部调用自身的方法。
Example:
例子:
public void recur(int x)
recur(10);
end
回答by Jason Sturges
Recursion is when a function calls itself:
递归是当函数调用自身时:
int factorial(int integer)
{
if (integer == 1)
return 1;
else
return (integer*(factorial(integer-1)));
}