递归 尾递归_什么是尾递归?

本文深入讲解尾递归的概念,解释为什么尾递归函数更优,以及如何通过改变递归调用为循环结构来消除尾递归。并以汉诺塔问题为例,对比有尾递归和无尾递归的函数实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

递归 尾递归

Here you will learn about what is tail recursion with example.

在这里,您将通过示例了解什么是尾递归。

Tail recursion refers to recursive call at last line. The tail recursive functions considered better as the recursive call is at the last statement so there is nothing left to do in the current function. It saves the current function’s stack frame is of no use.

尾递归是指最后一行的递归调用。 尾部递归函数被认为更好,因为递归调用位于最后一条语句中,因此当前函数中无事可做。 保存当前函数的堆栈框架是没有用的。

Tail recursion can be eliminated by changing the recursive call to a goto preceded by a set of assignments per function call. This simulates the recursive call because nothing needs to be saved after the recursive call finishes. We can just goto the top of the function with the values that would have been used in a recursive call.

通过将递归调用更改为goto,并在每个函数调用之前分配一组分配,可以消除尾递归。 这模拟了递归调用,因为在递归调用完成之后不需要保存任何内容。 我们可以使用递归调用中使用的值转到函数顶部。

What is Tail Recursion?
Image Source图片来源
Tower of Honoi Problem is given below. It is an example of recursive function with tail recursion. 了Honoi问题塔的递归函数。 这是带有尾递归的递归函数的示例。

带有尾递归的递归函数TOH (Recursive Function TOH with Tail Recursion)

void TOH(int n,char x,char y,char z)
{
	if(n>0)
	{
		TOH(n-1,x,z,y);
		printf("\n%c-> %c",x,y);
		TOH(n-1,z,y,x);		//tail recursion
	}
}

没有尾递归 (Without Tail Recursion)

void TOH(int n,char x,char y,char z)
{
	char temp;
	label:
	if(n>0)
	{
		TOH(n-1,x,z,y);
		printf("\n%c-> %c",x,y);
		temp=x;
		x=z;
		z=temp;
		n=n-1;
		goto label;
	}
}

翻译自: https://www.thecrazyprogrammer.com/2014/07/what-is-tail-recursion.html

递归 尾递归

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值