Sponsored
Sponsored
The dynamic programming approach breaks the problem into smaller, more manageable sub-problems. We then solve each sub-problem once, store its result, and use these results to construct the solution to the original problem in an efficient manner, avoiding repeated calculations.
Time Complexity: O(n)
Space Complexity: O(n)
1#include <iostream>
2#include <vector>
3using namespace std;
4
5int fibonacci(int n) {
6 vector<int> dp(n + 1, 0);
7 dp[1] = dp[2] = 1;
8 for (int i = 3; i <= n; i++) {
9 dp[i] = dp[i - 1] + dp[i - 2];
10 }
11 return dp[n];
12}
13
14int main() {
15 int n = 10;
16 cout << "Fibonacci number is " << fibonacci(n) << endl;
17 return 0;
18}
This C++ solution uses a vector to store Fibonacci numbers, employing dynamic programming to efficiently calculate the nth Fibonacci number by reducing redundant calculations.
The recursive approach with memoization involves using a recursive function to calculate Fibonacci numbers and memorizing results of previously computed terms. It reduces the overhead of repeated computations by storing results in a data structure (e.g., dictionary).
Time Complexity: O(n)
Space Complexity: O(n) due to memoization array.
Java uses a HashMap for memoization, storing precomputed Fibonacci numbers, thus reducing computations by leveraging previously stored results.