From bad9a578145a4d78764c31291e1463eb927a6155 Mon Sep 17 00:00:00 2001 From: Augusto Alves Date: Sun, 13 Oct 2019 13:58:56 +0100 Subject: [PATCH] Issue #1: Add Fibonacci Dynamic Programming --- Dynamic Programming/Fibonacci.java | 39 ++++++++++++++++++++++++++++++ 1 file changed, 39 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 0000000..3f94d5e --- /dev/null +++ b/Dynamic Programming/Fibonacci.java @@ -0,0 +1,39 @@ +/** + * This is a algorithm to implement the Fibonacci Nth element problem + * using dynamic programming paradigm. This version I am using the memoization + * strategy to going top-down to find all needed values and store on the fiboMemo array. + * + * @author Augusto Baltazar (augusto.jaba@gmail.com) + */ +public class Fibonacci { + + private int[] fiboMemo; + + private int findNthElement(int n) { + + if (this.fiboMemo == null) { + fiboMemo = new int[n + 1]; + } + + if (n <= 1) { + fiboMemo[n] = n; + } else { + fiboMemo[n] = findNthElement(n - 1) + findNthElement(n - 2); + } + + return fiboMemo[n]; + } + + /** + * Tests the function to the given number passed as argument + * @param args + */ + public static void main(String[] args) { + try { + int arg = Integer.parseInt(args[0]); + System.out.println(new Fibonacci().findNthElement(arg)); + } catch (Exception e) { + System.out.println("The argument entered is not a valid integer number."); + } + } +}