From bb670a2cebd7f5af76957a5f46c962c82bf6995b Mon Sep 17 00:00:00 2001 From: yanglbme Date: Tue, 5 Feb 2019 13:10:40 +0800 Subject: [PATCH] fix: remove unnecesary assignation to fix #698 - Fix #698 - Thanks @lprone --- Dynamic Programming/Fibonacci.java | 72 +++++++++++++----------------- 1 file changed, 30 insertions(+), 42 deletions(-) diff --git a/Dynamic Programming/Fibonacci.java b/Dynamic Programming/Fibonacci.java index d177b5bb9..8f9326ba9 100644 --- a/Dynamic Programming/Fibonacci.java +++ b/Dynamic Programming/Fibonacci.java @@ -4,14 +4,13 @@ import java.util.HashMap; import java.util.Map; /** - * * @author Varun Upadhyay (https://github.com/varunu28) - * + * @author yanglbme (https://github.com/yanglbme) */ public class Fibonacci { - private static Map map = new HashMap(); + private static Map map = new HashMap<>(); public static void main(String[] args) throws Exception { @@ -26,13 +25,8 @@ public class Fibonacci { * 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 + * Outputs the nth fibonacci number **/ - - - - - private static int fibMemo(int n) { if (map.containsKey(n)) { return map.get(n); @@ -42,10 +36,9 @@ public class Fibonacci { if (n <= 2) { f = 1; - } - else { - f = fibMemo(n-1) + fibMemo(n-2); - map.put(n,f); + } else { + f = fibMemo(n - 1) + fibMemo(n - 2); + map.put(n, f); } return f; @@ -55,55 +48,50 @@ public class Fibonacci { * 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 + * Outputs the nth fibonacci number **/ - private static int fibBotUp(int n) { - Map fib = new HashMap(); + Map fib = new HashMap<>(); - for (int i=1;i + * This is optimized version of Fibonacci Program. Without using Hashmap and recursion. + * It saves both memory and time. + * Space Complexity will be O(1) + * Time Complexity will be O(n) + *

+ * Whereas , the above functions will take O(n) Space. + * @author Shoaib Rayeen (https://github.com/shoaibrayeen) **/ private static int fibOptimized(int n) { - if (n == 0) { return 0; } - int prev = 0 , res = 1 , next; - for ( int i = 2; i < n; i++) { - next = prev + res; - prev = res; - res = next; + int prev = 0, res = 1, next; + for (int i = 2; i < n; i++) { + next = prev + res; + prev = res; + res = next; } return res; } -} - +} \ No newline at end of file