Skip to content

Commit a3e657a

Browse files
committed
DP implemented for getting an Nth number in a fibonacci series
1 parent 1bbccba commit a3e657a

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.cs.dsa.dynamic_programming;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
public class FibonacciDP {
7+
// get the nth fibonacci series.
8+
private static int counter = 0;
9+
private static int counterDP = 0;
10+
11+
Map<Integer, Integer> memo = new HashMap();
12+
13+
public int getNthNumberOfFiboSeries(int n) {
14+
counter++;
15+
if(n <= 1) {
16+
return n;
17+
}
18+
return getNthNumberOfFiboSeries(n-1) + getNthNumberOfFiboSeries(n-2);
19+
}
20+
21+
public int getNthNumberOfFiboSeriesDP(int n) {
22+
counterDP++;
23+
if(n <= 1) {
24+
return n;
25+
}
26+
if(memo.containsKey(n)) {
27+
return memo.get(n);
28+
}
29+
int result = getNthNumberOfFiboSeriesDP(n-1) + getNthNumberOfFiboSeriesDP(n-2);
30+
memo.put(n, result);
31+
return result;
32+
}
33+
34+
public static void main(String[] args) {
35+
FibonacciDP fibonacciDP = new FibonacciDP();
36+
37+
System.out.println("1st is : " + fibonacciDP.getNthNumberOfFiboSeries(1));
38+
System.out.println("3rd is : " + fibonacciDP.getNthNumberOfFiboSeries(3));
39+
System.out.println("4th is : " + fibonacciDP.getNthNumberOfFiboSeries(4));
40+
System.out.println("5th is : " + fibonacciDP.getNthNumberOfFiboSeries(6));
41+
42+
System.out.println("Without DP (total), method called : " + counter);
43+
44+
System.out.println("5th is : " + fibonacciDP.getNthNumberOfFiboSeriesDP(5));
45+
System.out.println("6th is : " + fibonacciDP.getNthNumberOfFiboSeriesDP(4));
46+
System.out.println("With DP (total), method called : " + counterDP);
47+
48+
}
49+
}

0 commit comments

Comments
 (0)