# Difference between Brute Force and Dynamic Programming

Last Updated : 26 Mar, 2024

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 reaching the final answer.
• Brute force programming tests every possible routing combination; whereas other mathematical algorithms obtain the results more quickly when the number of test cases is large.
• Brute force techniques are not generally used in the industrial field because they are not optimal in terms of space and time and slow downs the overall product or software.

Dynamic Programming:

• The dynamic programming approach is similar to divide and conquer in breaking down the problem into smaller and yet smaller possible sub-problems. In simple words, dynamic programming is an optimization over simple recursion.
• But unlike divide and conquer, these sub-problems are not solved independently.
• Rather, the results of these smaller sub-problems are remembered and used for similarity or overlapping.

Different ways of using Dynamic Programming:

• Top-Down: Start solving the given problem by breaking it down. If we see that the problem has been solved already, then just return the saved answer. If it has not been solved, solve it and save the answer. This approach is also known as Memoization.
• Bottom-Up: Analyze the problem and see the order in which the sub-problems are solved and start solving from the trivial subproblem, up to the given problem. In this process, it is guaranteed that the subproblems are solved before solving the problem. This approach is also known as Tabulation.

Difference between Brute Force and Dynamic Programming: The difference between these two approaches is mentioned clearly in the following table.

Parameters of ComparisonBrute ForceDynamic Programming
MethodologyIt finds all the possible outcomes of a given problem.It also finds all the possible outcomes, but avoids recomputation by storing
solutions of the subproblems.
Time ComplexityIt could be anything, sometimes even in exponential terms.It helps us optimize the brute force approach, sometimes exponential terms are improved to polynomial terms(ex. factorial program).
IterationsThe number of iterations is moreThe number of iterations is less(in terms of n)
EfficiencyIt is less efficientIt is more efficient
StorageGenerally requires no extra space for storing results of sub-problems.It requires extra space for storing the solutions to the sub-problems, which could be further used when required.

Here is an example of brute force for finding Fibonacci of 15.

C++ ```#include <bits/stdc++.h> using namespace std; int Fibonacci(int n){ if(n==1) return 1; if(n==2) return 2; return Fibonacci(n-1)+Fibonacci(n-2); } int main() { int z=15; cout<<Fibonacci(15); } ``` Java ```// Java program to calculate the nth Fibonacci number using recursion public class Fibonacci { // Recursive function to calculate the nth Fibonacci number static int fibonacci(int n) { // Base case: if n is 1, return 1 if (n == 1) { return 1; } // Base case: if n is 2, return 2 if (n == 2) { return 2; } // Recursive case: calculate Fibonacci(n-1) + Fibonacci(n-2) return fibonacci(n - 1) + fibonacci(n - 2); } public static void main(String[] args) { // Specifying the value of n for which Fibonacci number needs to be calculated int n = 15; // Calling the Fibonacci function and printing the result System.out.println(fibonacci(n)); } } ``` C# ```using System; class Program { static int Fibonacci(int n) { if (n == 1) return 1; if (n == 2) return 2; return Fibonacci(n - 1) + Fibonacci(n - 2); } static void Main(string[] args) { Console.WriteLine(Fibonacci(15)); } } ``` Javascript ```function Fibonacci(n) { if (n === 1) { return 1; } if (n === 2) { return 2; } return Fibonacci(n - 1) + Fibonacci(n - 2); } const z = 15; console.log(Fibonacci(15)); ``` Python3 ```def Fibonacci(n): if n == 1: return 1 if n == 2: return 2 return Fibonacci(n-1) + Fibonacci(n-2) if __name__ == "__main__": z = 15 print(Fibonacci(15)) ```

Output
```987

```

Here is an example of dynamic programming for finding Fibonacci of 15

C++ ```#include <bits/stdc++.h> using namespace std; int Fibonacci(int n,vector<int>&dp){ if(n==1) return 1; if(n==2) return 2; if(dp[n]!=-1) return dp[n]; return dp[n]= Fibonacci(n-1,dp)+Fibonacci(n-2,dp); } int main() { int z=15; vector<int>dp(z+1,-1); cout<<Fibonacci(15,dp); } ``` Java ```import java.util.Arrays; import java.util.Vector; public class Main { // Function to calculate Fibonacci number with memoization static int Fibonacci(int n, Vector<Integer> dp) { // Base cases if (n == 1) return 1; if (n == 2) return 2; // If already calculated, return the stored value if (dp.get(n) != -1) return dp.get(n); // Calculate Fibonacci number recursively int fib = Fibonacci(n - 1, dp) + Fibonacci(n - 2, dp); // Store the calculated value for future use dp.set(n, fib); return fib; } public static void main(String[] args) { int z = 15; // Create a vector to store computed Fibonacci numbers with initial values as -1 Vector<Integer> dp = new Vector<>(Arrays.asList(new Integer[z + 1])); for (int i = 0; i <= z; i++) { dp.set(i, -1); } // Calculate and print Fibonacci(15) System.out.println(Fibonacci(15, dp)); // Output should be 987 } } //This code is contributed by Adarsh. ``` JavaScript ```// Function to calculate the nth Fibonacci number using memoization function Fibonacci(n, dp) { // Base cases: F(1) = 1, F(2) = 2 if (n === 1) return 1; if (n === 2) return 2; // If the value is already calculated, return it from the dp array if (dp[n] !== -1) return dp[n]; // Otherwise, calculate and store the Fibonacci number in the dp array return dp[n] = Fibonacci(n - 1, dp) + Fibonacci(n - 2, dp); } // Main function function main() { // Define the value of z let z = 15; // Initialize the dp array with -1 let dp = new Array(z + 1).fill(-1); // Output the 15th Fibonacci number console.log(Fibonacci(15, dp)); } // Call the main function main(); ``` Python3 ```def fibonacci(n, dp): """ Function to calculate the nth Fibonacci number using memoization Args: - n: Integer, the index of the Fibonacci number to calculate - dp: List, memoization table to store previously calculated Fibonacci numbers Returns: - Integer, the nth Fibonacci number """ # Base cases if n == 1: return 1 if n == 2: return 2 # Check if the Fibonacci number has already been calculated if dp[n] != -1: return dp[n] # Calculate the Fibonacci number recursively dp[n] = fibonacci(n - 1, dp) + fibonacci(n - 2, dp) return dp[n] def main(): """ Main function to demonstrate Fibonacci calculation using memoization """ z = 15 # Calculate Fibonacci number for index 15 dp = [-1] * (z + 1) # Initialize memoization table print(fibonacci(15, dp)) if __name__ == "__main__": main() ```

Output
```987

```