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

Popular posts from this blog

Java important topics list for interviews

Tough Sql practise questions for interviews involving SELECT queries - Part 2

DBMS important topics list for interviews

Program to find number lines and words in a given file

Tough Sql practise questions for interviews involving SELECT queries - Part 1

Producer Consumer Problem with Blocking Queue in Java.

Animation for String search - KMP Algorithm

Interactive Data Structure visualizations/animations for algorithms

Replace Occurances of the given string