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)
1function fibonacci(n) {
2 let dp = new Array(n + 1).fill(0);
3 dp[1] = dp[2] = 1;
4 for (let i = 3; i <= n; i++) {
5 dp[i] = dp[i - 1] + dp[i - 2];
6 }
7 return dp[n];
8}
9
10let n = 10;
11console.log("Fibonacci number is " + fibonacci(n));
JavaScript leverages dynamic programming by using an array to trace Fibonacci numbers, ensuring efficient computation of the nth Fibonacci number by avoiding unnecessary recalculations.
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.
using System.Collections.Generic;
class Fibonacci {
static Dictionary<int, int> memo = new Dictionary<int, int>();
public static int Fibonacci(int n) {
if (n <= 2) return 1;
if (memo.ContainsKey(n)) return memo[n];
memo[n] = Fibonacci(n - 1) + Fibonacci(n - 2);
return memo[n];
}
static void Main() {
int n = 10;
Console.WriteLine("Fibonacci number is " + Fibonacci(n));
}
}
The C# approach uses a Dictionary for memoization, optimizing the recursive Fibonacci calculation by storing previously determined numbers for future use.