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
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 :)
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];
}