head & 的区别尾递归 [英] The difference between head & tail recursion
问题描述
我正在尝试找出这两种递归策略之间的区别.
I'm trying to get the difference between these 2 recursive strategies.
我被告知的定义如下:
尾递归:如果调用返回后无需执行任何操作,即调用返回时,调用函数立即返回返回值,则调用是尾递归的
Tail Recursion: A call is tail-recursive if nothing has to be done after the call returns i.e. when the call returns, the returned value is immediately returned from the calling function
头递归:当函数的第一条语句是递归调用时,调用就是头递归.
Head Recursion: A call is head-recursive when the first statement of the function is the recursive call.
推荐答案
在 head recursion
中,递归调用,当它发生时,在函数中的其他处理之前(想想它发生在函数的顶部或头部).
In head recursion
, the recursive call, when it happens, comes before other processing in the function (think of it happening at the top, or head, of the function).
在尾递归
中,情况正好相反——处理发生在递归调用之前.在这两种递归风格之间进行选择似乎是随意的,但选择可以产生很大的不同.
In tail recursion
, it’s the opposite—the processing occurs before the recursive call. Choosing between the two recursive styles may seem arbitrary, but the choice can make all the difference.
在路径开头有一个单一递归调用的路径的函数使用所谓的头递归.先前展示的阶乘函数使用头部递归.一旦确定需要递归,它所做的第一件事就是用递减的参数调用自己.在路径末尾具有单个递归调用的函数使用尾递归.参考这篇文章
A function with a path with a single recursive call at the beginning of the path uses what is called head recursion. The factorial function of a previous exhibit uses head recursion. The first thing it does once it determines that recursion is needed is to call itself with the decremented parameter. A function with a single recursive call at the end of a path is using tail recursion. Refer this article
示例递归:
public void tail(int n) | public void head(int n)
{ | {
if(n == 1) | if(n == 0)
return; | return;
else | else
System.out.println(n); | head(n-1);
|
tail(n-1); | System.out.println(n);
} | }
如果递归调用发生在方法的末尾,则称为尾递归
.尾递归类似于循环
.方法在跳转到下一个递归调用之前执行所有语句
.
If the recursive call occurs at the end of a method, it is called a tail recursion
. The tail recursion is similar to a loop
. The method executes all the statements before jumping into the next recursive call
.
如果递归调用发生在方法的开头,则称为头递归
.方法在跳转到下一个递归调用之前保存状态
.
If the recursive call occurs at the beginning of a method, it is called a head recursion
. The method saves the state before jumping into the next recursive call
.
这篇关于head & 的区别尾递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!