The Fibonacci sequence is a sequence of numbers in which each number after the first two is the sum of the two preceding ones. In mathematical terms, it can be defined as:
F(n) = F(n-1) + F(n-2), where F(0) = 0 and F(1) = 1.
A straightforward recursive solution to this problem looks like this:
int fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
However, this solution is inefficient for large values of n since it recomputes the same values multiple times. Dynamic programming can help us improve the efficiency of this algorithm by storing the results of previously computed values and reusing them if necessary.
Here’s the bottom-up approach to implementing the Fibonacci sequence using dynamic programming:
public static int fibonacci(int n) {
if (n <= 1) {
return n;
}
int[] memo = new int[n + 1];
memo[0] = 0;
memo[1] = 1;
for (int i = 2; i <= n; i++) {
memo[i] = memo[i - 1] + memo[i - 2];
}
return memo[n];
}
In this solution, we create an array called memo to store the results of previously computed Fibonacci numbers. We start by initializing memo[0] and memo[1] to their respective values in the sequence.
We then use a loop to iterate from i=2 up to n, computing and storing each new Fibonacci number in the memo array. By the time we reach the end of the loop, memo[n] will contain the desired Fibonacci number.
This approach has a time complexity of O(n) and a space complexity of O(n), which is more efficient than the recursive approach discussed earlier.