Recursive Fibonacci memoization

后端 未结 14 1404
走了就别回头了
走了就别回头了 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:31

    I believe you forget to actually look up stuff in your dictionary.

    Change

    else
        return dictionary[n] = fibonacci(n-1) + fibonacci(n-2);
    

    to

    else {
        if (dictionary[n] > 0)
            return dictionary[n];
    
        return dictionary[n] = fibonacci(n - 1) + fibonacci(n - 2);
    }
    

    and it works just fine (tested it myself :)

    0 讨论(0)
  • 2020-11-30 03:31

    Here is my implementation.

    private static int F(int N, int[] A) {
        if ((N == 0) || (N == 1)) return N;
        if (A[N] != 0) return A[N];
    
        if ((A[N - 1] != 0) && (A[N - 2] != 0)) {
            A[N] = A[N - 1] + A[N - 2];
            return A[N];
        }
    
        if (A[N-2] != 0) {
            A[N] = A[N - 2] + F(N - 1, A);
            return A[N];
        }
        if (A[N-1] != 0) {
            A[N] = A[N - 1] + F(N - 2, A);
            return A[N];
        }
        A[N] = F(N-1, A) + F(N-2, A);
        return A[N];
    }
    
    0 讨论(0)
提交回复
热议问题