尾递归
函数递归调用自身的技巧叫做递归
递归是很神奇的概念。所有学编程和有志于解答世上最复杂的难题的人,都一定要好好理解一下什么是递归。
而尾递归是一种我们通常称之为“迭代”的递归方式。这篇文章无法确切地教给你到底什么是递归什么是尾递归,因为它们的真正含义需要有志者仔细体会。
尾递归
尾递归是带着一个“迭代变量”不断向深处递归,相当于边递归,边计算,等递归完成时,结果也计算出来了。
In computer science, a tail call is a subroutine call performed as the final action of a procedure. If the target of a tail is the same subroutine, the subroutine is said to be tail-recursive, which is a special case of direct recursion. Tail recursion (or tail-end recursion) is particularly useful, and often easy to handle in implementations.
尾递归是返回递归关系最后一个动作的递归方式。
而递归中不计算任何值,到最后Return时递归求解。
递归和迭代(尾递归)的Fibonacci Numbers实现
## The Recursion and Iteration implemention by qianxin
## Dedicated to Fibonacci(1170—1250)
## Recursion Fibonacci Numbers
def Rfib(i):
if(i == 1 or i == 2):
return 1
else:
return Rfib(i-1)+Rfib(i-2)
## Iteration Fibonacci Numbers
def Ifib(i, a, b):
if(i == 1 or i == 2):
# That's a Iteration! By Tail Recursion
return b
else:
return Ifib(i-1, b, a+b)
献给Fibonacci(1170—1250)。

浙公网安备 33010602011771号