头与头之间的区别尾递归 [英] The difference between head & tail recursion

查看:314
本文介绍了头与头之间的区别尾递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图区分这两种递归策略。

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:当函数的第一个语句是递归调用时,调用是头递归的。

Head Recursion: A call is head-recursive when the first statement of the function is the recursive call.

推荐答案

头部递归中,递归调用,当它发生时,在函数中的其他处理之前出现(想想它发生在功能的顶部或头部)。

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.

这篇关于头与头之间的区别尾递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆