Fibonacci series solved as Dynamic programming - Memoization approach
Fibonacci series solved as Dynamic programming:
/**
* Fibonacci series: 1, 1, 2, 3, 5, 8
*/
public class FibonacciDP {
private static final int MAX = 1000;
private Integer[] lookup = new Integer[1000];
public FibonacciDP() {
init();
}
private void init() {
for (int i = 0; i < MAX; i++) {
lookup[i] = -1;
}
}
/**
* Function to find nth fibonacci number.
*/
int fib(int n) {
if (lookup[n] == -1) {
if (n <= 1) {
lookup[n] = 1;
} else {
lookup[n] = fib(n - 1) + fib(n - 2);
}
}
return lookup[n];
}
public static void main(String[] args) {
int n = 3;
System.out.println(new FibonacciDP().fib(n));
}
}
Comments
Post a Comment