Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
My journey with you | All you wish will be here !!!
My journey with you | All you wish will be here !!!
Dynamic Programming (DP) is a technique used to solve problems by breaking them down into smaller subproblems and storing the results of these subproblems to avoid redundant calculations.
Recursive Fibonacci:
javaCopy codepublic class Fibonacci {
public static int fib(int n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
public static void main(String[] args) {
System.out.println("Fibonacci of 5: " + fib(5));
}
}
Dynamic Programming Fibonacci:
javaCopy codepublic class Fibonacci {
public static int fib(int n) {
int[] dp = new int[n + 1];
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
public static void main(String[] args) {
System.out.println("Fibonacci of 5: " + fib(5));
}
}