From 0d4cfbabe6786dd5b0ec8de05c9a864f648d85e7 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Mon, 4 Sep 2017 14:08:12 -0700 Subject: [PATCH 1/2] Added Fibanacci using memoization --- Dynamic Programming/Fibonacci.java | 49 ++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Dynamic Programming/Fibonacci.java diff --git a/Dynamic Programming/Fibonacci.java b/Dynamic Programming/Fibonacci.java new file mode 100644 index 00000000..844beabb --- /dev/null +++ b/Dynamic Programming/Fibonacci.java @@ -0,0 +1,49 @@ +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 { + + public static Map map = new HashMap(); + + public static void main(String[] args) throws Exception { + + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int n = Integer.parseInt(br.readLine()); + + System.out.println(fib(n)); // Returns 8 for n = 6 + } + + /** + * 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 + **/ + + public static int fib(int n) { + if (map.containsKey(n)) { + return map.get(n); + } + + int f; + + if (n <= 2) { + f = 1; + } + else { + f = fib(n-1) + fib(n-2); + map.put(n,f); + } + + return f; + } +} + From 73e05940eae0a46fa4921ef1ecfb81fab4f91a76 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Mon, 4 Sep 2017 14:40:12 -0700 Subject: [PATCH 2/2] Added bottom up approach --- Dynamic Programming/Fibonacci.java | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/Dynamic Programming/Fibonacci.java b/Dynamic Programming/Fibonacci.java index 844beabb..72048153 100644 --- a/Dynamic Programming/Fibonacci.java +++ b/Dynamic Programming/Fibonacci.java @@ -18,7 +18,8 @@ public class Fibonacci { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); - System.out.println(fib(n)); // Returns 8 for n = 6 + System.out.println(fibMemo(n)); // Returns 8 for n = 6 + System.out.println(fibBotUp(n)); // Returns 8 for n = 6 } /** @@ -28,7 +29,7 @@ public class Fibonacci { * Outputs the nth fibonacci number **/ - public static int fib(int n) { + public static int fibMemo(int n) { if (map.containsKey(n)) { return map.get(n); } @@ -45,5 +46,30 @@ public class Fibonacci { return f; } + + /** + * 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 + **/ + + public static int fibBotUp(int n) { + + Map fib = new HashMap(); + + for (int i=1;i