public int tailRecursive(final int n) {if (n <= 2)return 1;return tailRecursiveAux(n, 1, 1);}
private int tailRecursiveAux(int n, int iter, int acc) {if (iter == n)return acc;return tailRecursiveAux(n, ++iter, acc + iter);}
将此与标准递归实现进行对比:
public int recursive(final int n) {if (n <= 2)return 1;return recursive(n - 1) + recursive(n - 2);}
def factorial(number):if number == 1:# BASE CASEreturn 1else:# RECURSIVE CASE# Note that `number *` happens *after* the recursive call.# This means that this is *not* tail call recursion.return number * factorial(number - 1)
这是阶乘函数的尾调用递归版本:
def factorial(number, accumulator=1):if number == 0:# BASE CASEreturn accumulatorelse:# RECURSIVE CASE# There's no code after the recursive call.# This is tail call recursion:return factorial(number - 1, number * accumulator)print(factorial(5))
function Factorial(x) {//Base case x<=1if (x <= 1) {return 1;} else {// x is waiting for the return value of Factorial(x-1)// the last thing we do is NOT applying the recursive call// after recursive call we still have to multiply.return x * Factorial(x - 1);}}
我们的调用堆栈中有4个调用。
Factorial(4); // waiting in the memory for Factorial(3)4 * Factorial(3); // waiting in the memory for Factorial(2)4 * (3 * Factorial(2)); // waiting in the memory for Factorial(1)4 * (3 * (2 * Factorial(1)));4 * (3 * (2 * 1));
我们正在进行4次阶乘()调用,空间为O(n)
这可能会导致Stackoverflow
尾递归阶乘
function tailFactorial(x, totalSoFar = 1) {//Base Case: x===0. In recursion there must be base case. Otherwise they will never stopif (x === 0) {return totalSoFar;} else {// there is nothing waiting for tailFactorial to complete. we are returning another instance of tailFactorial()// we are not doing any additional computaion with what we get back from this recursive callreturn tailFactorial(x - 1, totalSoFar * x);}}