Difference between Recursion and Dynamic Programming
Last Updated :
17 Jan, 2024
Recursion and Dynamic programming are two effective methods for solving big problems into smaller, more manageable subproblems. Despite their similarities, they differ in some significant ways.
Below is the Difference Between Recursion and Dynamic programming in Tabular format:
|
By breaking a difficulty down into smaller problems of the same problem, a function calls itself to solve the problem until a specific condition is met.
| It is a technique by breaks them into smaller problems and stores the results of these subproblems to avoid repeated calculations.
|
Recursion frequently employs a top-down method in which the primary problem is broken down into more manageable subproblems.
| Using a bottom-up methodology, dynamic programming starts by resolving the smallest subproblems before moving on to the primary issue.
|
To avoid infinite loops, it is necessary to have a base case (termination condition) that stops the recursion when a certain condition is satisfied.
| Although dynamic programming also needs a base case, it focuses mostly on iteratively addressing subproblems.
|
Recursion might be slower due to the overhead of function calls and redundant calculations.
| Dynamic programming is often faster due to optimized subproblem solving and memoization.
|
It does not require extra memory, only requires stack space
| Dynamic programming require additional memory to record intermediate results.
|
It include computing factorials, using the Fibonacci sequence.
| It include computing the nth term of a series using bottom-up methods, the knapsack problem
|
Let's take an example: Find out the Nth Fibonacci number
1) Using Recursion:
Below is the code of Fibonacci series using recursion:
C++
#include <iostream>
int fibonacci_recursive(int n) {
if (n <= 1) {
return n;
} else {
return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2);
}
}
int main() {
int n = 5;
int result = fibonacci_recursive(n);
std::cout << result << std::endl;
return 0;
}
Java
public class GFG {
// Recursive function to calculate the nth Fibonacci number
public static int fibonacciRecursive(int n) {
if (n <= 1) {
// Base case: Fibonacci of 0 is 0, and Fibonacci of 1 is 1
return n;
} else {
// Recursively calculate Fibonacci for n-1 and n-2
return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2);
}
}
public static void main(String[] args) {
int n = 5;
int result = fibonacciRecursive(n);
System.out.println(result);
}
}
Python
def fibonacci_recursive(n):
if n <= 1:
return n
else:
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
print(fibonacci_recursive(5))
C#
using System;
public class Solution
{
public int FibonacciRecursive(int n)
{
if (n <= 1)
{
return n;
}
else
{
return FibonacciRecursive(n - 1) + FibonacciRecursive(n - 2);
}
}
static void Main()
{
Solution solution = new Solution();
Console.WriteLine(solution.FibonacciRecursive(5));
}
}
JavaScript
function fibonacciRecursive(n) {
if (n <= 1) {
return n;
} else {
return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2);
}
}
const n = 5;
const result = fibonacciRecursive(n);
console.log(result);
Time Complexity: O(2n), which is highly inefficient.
Auxiliary Space: Recursion consumes memory on the call stack for each function call, which can also lead to high space complexity. Inefficient recursive algorithms can lead to stack overflow errors.
2) Using Dynamic Programming:
Below is the code of Fibonacci series using Dynamic programming:
C++
#include <iostream>
#include <vector>
int fibonacci_dp(int n) {
std::vector<int> fib(n + 1, 0);
fib[1] = 1;
for (int i = 2; i <= n; ++i) {
fib[i] = fib[i - 1] + fib[i - 2];
}
return fib[n];
}
int main() {
std::cout << fibonacci_dp(5) << std::endl;
return 0;
}
Java
import java.util.Arrays;
public class FibonacciDP {
static int fibonacciDP(int n) {
int[] fib = new int[n + 1];
fib[1] = 1;
for (int i = 2; i <= n; ++i) {
fib[i] = fib[i - 1] + fib[i - 2];
}
return fib[n];
}
public static void main(String[] args) {
System.out.println(fibonacciDP(5));
}
}
Python
def fibonacci_dp(n):
fib = [0] * (n + 1)
fib[1] = 1
for i in range(2, n + 1):
fib[i] = fib[i - 1] + fib[i - 2]
return fib[n]
print(fibonacci_dp(5))
C#
using System;
class Program
{
// Function to calculate the nth Fibonacci number using dynamic programming
static int FibonacciDP(int n)
{
// Create an array to store Fibonacci numbers
int[] fib = new int[n + 1];
// Initialize the first two Fibonacci numbers
fib[1] = 1;
// Calculate Fibonacci numbers from the bottom up
for (int i = 2; i <= n; ++i)
{
fib[i] = fib[i - 1] + fib[i - 2];
}
// Return the nth Fibonacci number
return fib[n];
}
static void Main()
{
// Test the FibonacciDP function with n = 5
Console.WriteLine(FibonacciDP(5));
}
}
JavaScript
function fibonacci_dp(n) {
const fib = new Array(n + 1).fill(0);
fib[1] = 1;
for (let i = 2; i <= n; ++i) {
fib[i] = fib[i - 1] + fib[i - 2];
}
return fib[n];
}
console.log(fibonacci_dp(5));
Time Complexity: O(n), a vast improvement over the exponential time complexity of recursion.
Auxiliary Space: DP may have higher space complexity due to the need to store results in a table. In the Fibonacci example, it's O(n) for the storage of the Fibonacci sequence.
Application of Recursion:
- Finding the Fibonacci sequence
- Finding the factorial of a number
- Binary tree traversals such as in-order, pre-order, and post-order traversals.
Application of Dynamic Programming:
- Calculation of Fibonacci numbers and storing the results
- Finding longest subsequences
- To identify the shortest pathways in graphs, dynamic programming techniques like Dijkstra's.
Conclusion:
Recursion and dynamic programming both use common problem-solving techniques, although they focus differently on optimisation and memory usage. The nature of the issue and the intended outcome of the solution will determine which option is best.
Similar Reads
Difference between Recursion and Iteration A program is called recursive when an entity calls itself. A program is called iterative when there is a loop (or repetition).Example: Program to find the factorial of a number C++ // C++ program to find factorial of given number #include<bits/stdc++.h> using namespace std; // ----- Recursion
6 min read
Difference between Brute Force and Dynamic Programming Brute Force: It gives a solution to a problem by using the most straightforward method. However, it is typically not a very optimal solution or one that is flexible for future changes, but it gets the job done. The proverbial brute force programming example is trying all optimal solutions for reachi
6 min read
Difference Between Recursion and Induction Recursion and induction are fundamental ideas in computer science and mathematics that might be regularly used to solve problems regarding repetitive structures. Recursion is a programming technique in which a function calls itself to solve the problem, whilst induction is a mathematical proof techn
4 min read
Difference Between Recursive and Explicit In programming, recursive and explicit are two different approaches used to define functions or algorithms. The Recursive refers to the function that calls itself to solve smaller instances of same problem in while explicit refers to the function that directly defines the solution without relying on
6 min read
Difference between For, While and Do-While Loop in Programming For Loop, While Loop, and Do-While Loop are different loops in programming. A For loop is used when the number of iterations is known. A While loop runs as long as a condition is true. A Do-While loop runs at least once and then continues if a condition is true. For Loop in Programming:The for loop
5 min read
Difference Between For Loop and Do while Loop in Programming For loop and Do while loop are control flow structures in programming that allow you to repeatedly execute a block of code. However, they differ in their syntax and use cases. It is important for a beginner to know the key differences between both of them. For Loop in Programming:The for loop is use
4 min read
Difference between For Loop and While Loop in Programming Both for loops and while loops are control flow structures in programming that allow you to repeatedly execute a block of code. However, they differ in their syntax and use cases. It is important for a beginner to know the key differences between both of them. Difference between For Loop and While L
3 min read
Dynamic Programming vs Divide-and-Conquer In this article Iâm trying to explain the difference/similarities between dynamic programming and divide and conquer approaches based on two examples: binary search and minimum edit distance (Levenshtein distance).The ProblemWhen I started to learn algorithms it was hard for me to understand the mai
12 min read
What is the difference between Backtracking and Recursion? What is Recursion?The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function.Real Life ExampleImagine we have a set of boxes, each containing a smaller box. To find an item, we open the outermost box and conti
4 min read