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)
1def fibonacci(n):
2 dp = [0] * (n + 1)
3 dp[1], dp[2] = 1, 1
4 for i in range(3, n + 1):
5 dp[i] = dp[i - 1] + dp[i - 2]
6 return dp[n]
7
8n = 10
9print("Fibonacci number is", fibonacci(n))
This Python implementation uses a list to track already computed Fibonacci numbers and applies the principles of dynamic programming to avoid 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.
#include <vector>
using namespace std;
vector<int> memo(100, 0);
int fibonacci(int n) {
if (n <= 2) return 1;
if (memo[n] != 0) return memo[n];
return memo[n] = fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int n = 10;
cout << "Fibonacci number is " << fibonacci(n) << endl;
return 0;
}
This C++ solution stores calculated values in a vector to avoid redundant computation in recursive Fibonacci number determination, improving performance via memoization.