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 <stdio.h>
2#define MAX 100
3
4int fibonacci(int n) {
5 int dp[MAX] = {0};
6 dp[1] = dp[2] = 1;
7 for (int i = 3; i <= n; i++) {
8 dp[i] = dp[i - 1] + dp[i - 2];
9 }
10 return dp[n];
11}
12
13int main() {
14 int n = 10;
15 printf("Fibonacci number is %d\n", fibonacci(n));
16 return 0;
17}
This C code implements a dynamic programming solution to calculate the nth Fibonacci number. An array is utilized to store previously computed Fibonacci values, allowing the function to build on these stored results and compute higher terms efficiently.
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.
1
This recursive C solution uses an array for memoization to store already computed values, preventing recalculations and optimizing the Fibonacci computation.