![]() |
VOOZH | about |
Dynamic Programming (DP) is a technique used to solve problems by breaking them into smaller subproblems and storing their results for later use.
In the recursion tree for the Fibonacci example, the same subproblems appear repeatedly. For instance, values such as F(2), F(3) and F(4) are recomputed multiple times. This repeated work causes the naive recursive solution to grow exponentially in time as n becomes larger.
Dynamic Programming improves this by solving each subproblem once and reusing the stored result.
Dynamic Programming can be implemented using two main approaches:
In the top-down approach, we start with the original problem and solve smaller subproblems recursively. The results of solved subproblems are stored so they can be reused when needed again.
In the bottom-up approach, we solve the smallest subproblems first and use their results to build the solution for larger subproblems.
To know more about DP, refer to this article When to Use Dynamic Programming (DP)
Let's understand Dynamic Programming using the Fibonacci Sequence, where each number is the sum of the previous two numbers. Fibonacci Sequence:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
The Fibonacci formula is:
F(n) = F(n - 1) + F(n - 2)
Where:
A simple recursive solution calculates each Fibonacci number by repeatedly computing the previous two Fibonacci numbers.
5
Below is the recursion tree of the above recursive solution:
In the memoization approach, we use recursion along with a memoization array (memo) to store already calculated Fibonacci values. Before solving a subproblem, we first check whether its result is already available in the array. If it is available, we reuse it directly; otherwise, we calculate it and store the result for future use.
5
Explanation:
In the tabulation approach, we solve the problem in a bottom-up manner. We start with the known Fibonacci values and store them in a DP array. Then, we build the remaining Fibonacci numbers one by one using the previously computed values until we reach the required term.
5
Explanation:
In the tabulation approach, we store all Fibonacci values in a DP array. However, each Fibonacci number depends only on the previous two values. So, instead of storing the entire array, we can keep track of just the last two Fibonacci numbers and use them to calculate the next value.
5
Explanation: