-8

无论我做什么,我都无法做到这一点。

返回具有第一个 len 斐波那契数的大小为 len 的 int[]。例如:n=6,返回 {1,1,2,3,5,8}。(前提:n>=2)

fibonacci(3) → {1, 1, 2}
fibonacci(6) → {1, 1, 2, 3, 5, 8}
fibonacci(8) → {1, 1, 2, 3, 5, 8, 13, 21}

这就是我所做的

if (n == 0) {
    return 0;
else if (n == 1)
    return 1;
else
    return fibonnaci(n - 1) + fibonnaci(n - 2);
4

3 回答 3

1
public static int[] FibLength(int l)
{
    int fib[] = new int[l];
    fib[0] = 1;
    fib[1] = 1;

    for (int i=2; i<fib.length; i++)
        fib[i] = fib[i-1] + fib[i-2];

    return fib;
}
于 2013-05-27T21:56:31.000 回答
1

迭代版本:

public int[] sonOfBonacci(int n) {
    int[] result = new int[n];
    result[0] = 1;
    if (n > 1) {
        result[1] = 1;
        for (int j = 1; j < n - 1; j++) {
            result[j + 1] = result[j - 1] + result[j];
        }
    }
    return result;
}
于 2013-05-27T21:59:00.157 回答
0

使用大数字:

public static void main(String[] args) {

    // Precalculate enough fibs
    List<BigInteger> list = new ArrayList<BigInteger>();
    list.add(BigInteger.ONE);
    list.add(BigInteger.ONE);
    for (int i = 2; i < 512; i++) {
        list.add(list.get(i - 2).add(list.get(i - 1)));
    }

    // Print first 10
    for (int n = 2; n <= 10; n++) {
        System.out.printf("fibonacci(%d)\t→\t%s%n", n, list.subList(0, n));
    }

}

输出:

fibonacci(2)    →   [1, 1]
fibonacci(3)    →   [1, 1, 2]
fibonacci(4)    →   [1, 1, 2, 3]
fibonacci(5)    →   [1, 1, 2, 3, 5]
fibonacci(6)    →   [1, 1, 2, 3, 5, 8]
fibonacci(7)    →   [1, 1, 2, 3, 5, 8, 13]
fibonacci(8)    →   [1, 1, 2, 3, 5, 8, 13, 21]
fibonacci(9)    →   [1, 1, 2, 3, 5, 8, 13, 21, 34]
fibonacci(10)   →   [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
于 2013-05-27T22:04:02.460 回答