我理解尾遞歸,但我已被分配編寫代碼來查看第N個斐波那契數是什麼。 開始,這段代碼確實有效。這不是最好的方式,但它是一種方式 - 但是我開始擔心它不是尾遞歸。該代碼是在這裏:調用本身返回兩次 - 尾遞歸還是不是?
static int fib_tail_helper(int n, int result) {
if (n == 0) {
return result;
}
else if (result == 0) {
return fib_tail_helper(n - 1, result + 1);
}
else {
return fib_tail_helper(n - 1, result + fib_tail_helper(n - 1, 0));
}
}
int fib_tail(int n) {
/*
// REQUIRES: n >= 0
// EFFECTS: computes the Nth Fibonacci number
// fib(0) = 0
// fib(1) = 1
// fib(n) = fib(n-1) + fib(n-2) for (n>1).
// MUST be tail recursive
*/
return fib_tail_helper(n, 0);
}
我主要是擔心 「迴歸fib_tail_helper(N - 1,結果+ fib_tail_helper(N - 1),0」 我覺得,如果將使用另一種。棧,從而成爲非尾遞歸...誰能給一些輸入?
謝謝!
如果你想確定檢查編譯器輸出。 – dtech 2014-09-19 23:07:32