我有以下递归斐波那契数列的代码
if (term < 2){
System.out.print("1 ");
return 1;
}
int results = fibonacci(term - 1) + fibonacci(term - 2);
System.out.print(results + " ");
return results;
我得到的输出是
斐波那契数列中你最喜欢什么项:4
1 1 2 1 3 1 1 2 5 第 4 个是 5
如何打印出来
1 1 2 3 第 4 个是 5
最佳答案
使用尾递归。
public static void main(String[] args) {
System.out.print("The 10th is: " + fibonnaci(10));
}
public static int fibonnaci(int number) {
return fibonnaciHelper(number, 1, 1);
}
public static int fibonnaciHelper(int term, int lower, int higher) {
if (term < 2){
return higher;
}
System.out.print(higher + " ");
int results = fibonnaciHelper(term - 1, higher, higher + lower);
return results;
}
关于java - 递归斐波那契数列打印列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16202346/