我得到了关于生成fib数的问题。我看到的纤维数的递归实现总是从上到下像fib(n)= fib(n-1)+ fib(n-2)但这个问题假设是fib(n-1),fib( n-2)存在计算下一个等等。
public class Fibonacci {
int[] fiboNums;
public Fibonacci(int n) {
// TODO: generate the first n fibonacci numbers
}
private void generateNextFibo(int n, int lastFibo, int lastLastFibo) {
// TODO: Implement this recursive function to compute next
// fibonacci number.
}
public int[] getAll() {
return fiboNums;
}
}
答案 0 :(得分:3)
第一个棘手的部分是需要调用传递params generateNextFibo的内容。第二部分是generateNextFibo方法的退出条件。
public class Fibonacci {
int fiboNums[];
public Fibonacci(int n) {
// generate the first n fibonacci numbers
fiboNums = new int[n];
fiboNums[0] = 1;
fiboNums[1] = 1;
// Start from 3 since the first two fibo numbers are given
if (n >= 3)
generateNextFibo(3, fiboNums[1], fiboNums[0]);
}
private void generateNextFibo(int n, int lastFibo, int lastLastFibo) {
// Implement this recursive function to compute next fibo number.
fiboNums[n - 1] = lastFibo + lastLastFibo;
if (fiboNums.length > n) {
lastLastFibo = lastFibo;
lastFibo = fiboNums[n - 1];
generateNextFibo(n + 1, lastFibo, lastLastFibo);
}
}
public int[] getAll() {
return fiboNums;
}
}