JavaAlgorithms/Dynamic Programming/Fibonacci.java

76 lines
1.7 KiB
Java
Raw Normal View History

2017-09-05 05:08:12 +08:00
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author Varun Upadhyay (https://github.com/varunu28)
*
*/
public class Fibonacci {
2017-10-04 00:26:07 +08:00
private static Map<Integer,Integer> map = new HashMap<Integer,Integer>();
2017-09-05 05:08:12 +08:00
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
2017-09-05 05:40:12 +08:00
System.out.println(fibMemo(n)); // Returns 8 for n = 6
System.out.println(fibBotUp(n)); // Returns 8 for n = 6
2017-09-05 05:08:12 +08:00
}
/**
* This method finds the nth fibonacci number using memoization technique
*
* @param n The input n for which we have to determine the fibonacci number
* Outputs the nth fibonacci number
**/
2017-10-04 00:26:07 +08:00
private static int fibMemo(int n) {
2017-09-05 05:08:12 +08:00
if (map.containsKey(n)) {
return map.get(n);
}
int f;
if (n <= 2) {
f = 1;
}
else {
2017-10-02 01:25:25 +08:00
f = fibMemo(n-1) + fibMemo(n-2);
2017-09-05 05:08:12 +08:00
map.put(n,f);
}
return f;
}
2017-09-05 05:40:12 +08:00
/**
* This method finds the nth fibonacci number using bottom up
*
* @param n The input n for which we have to determine the fibonacci number
* Outputs the nth fibonacci number
**/
2017-10-04 00:26:07 +08:00
private static int fibBotUp(int n) {
2017-09-05 05:40:12 +08:00
Map<Integer,Integer> fib = new HashMap<Integer,Integer>();
for (int i=1;i<n+1;i++) {
int f = 1;
if (i<=2) {
f = 1;
}
else {
f = fib.get(i-1) + fib.get(i-2);
}
fib.put(i, f);
}
return fib.get(n);
}
2017-09-05 05:08:12 +08:00
}