美文网首页
1.1.19 斐波那契数列

1.1.19 斐波那契数列

作者: 风亡小窝 | 来源:发表于2016-06-16 12:25 被阅读33次

原始的实现,有重复计算

public static long F(int N){
    if(N == 0) return 0;
    if(N == 1) return 1;
    return F(N-1) + F(N-2)
}

更好的实现,用数组保存已经计算过的值

    public static long fib(int n){
        long value[] = new long[n+1];
        value[1] = 1;
        long result = fibonacci(n, value);      
        return result;
    }
    
    public static long fibonacci(int n, long[] value){
        if (n==0) return 0;
        if (n==1) return 1;
        if(value[n]>1) return value[n];
        return value[n] = fibonacci(n-1, value) + fibonacci(n-2, value);
    }

相关文章

网友评论

      本文标题:1.1.19 斐波那契数列

      本文链接:https://www.haomeiwen.com/subject/wzymdttx.html