Recursive Fibonacci memoization

后端 未结 14 1460
走了就别回头了
走了就别回头了 2020-11-30 02:47

I need some help with a program I\'m writing for my Programming II class at universtiy. The question asks that one calculates the Fibonacci sequence using recursion. One mus

14条回答
  •  佛祖请我去吃肉
    2020-11-30 03:21

    Program to print first n fibonacci numbers using Memoization.

    int[] dictionary; 
    // Get Fibonacci with Memoization
    public int getFibWithMem(int n) {
        if (dictionary == null) {
            dictionary = new int[n];
        }
    
        if (dictionary[n - 1] == 0) {
            if (n <= 2) {
                dictionary[n - 1] = n - 1;
            } else {
                dictionary[n - 1] = getFibWithMem(n - 1) + getFibWithMem(n - 2);
            }
        }
    
        return dictionary[n - 1];
    }
    
    public void printFibonacci()
    {
        for (int curr : dictionary) {
            System.out.print("F[" + i++ + "]:" + curr + ", ");
        }
    }
    

提交回复
热议问题