Skip to content

Commit 0520547

Browse files
authored
Merge pull request darpanjbora#21 from augustojaba/augusto-baltazar-pr1
Issue darpanjbora#1: Add Fibonacci Dynamic Programming
2 parents ddac710 + bad9a57 commit 0520547

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Dynamic Programming/Fibonacci.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* This is a algorithm to implement the Fibonacci Nth element problem
3+
* using dynamic programming paradigm. This version I am using the memoization
4+
* strategy to going top-down to find all needed values and store on the fiboMemo array.
5+
*
6+
* @author Augusto Baltazar (augusto.jaba@gmail.com)
7+
*/
8+
public class Fibonacci {
9+
10+
private int[] fiboMemo;
11+
12+
private int findNthElement(int n) {
13+
14+
if (this.fiboMemo == null) {
15+
fiboMemo = new int[n + 1];
16+
}
17+
18+
if (n <= 1) {
19+
fiboMemo[n] = n;
20+
} else {
21+
fiboMemo[n] = findNthElement(n - 1) + findNthElement(n - 2);
22+
}
23+
24+
return fiboMemo[n];
25+
}
26+
27+
/**
28+
* Tests the function to the given number passed as argument
29+
* @param args
30+
*/
31+
public static void main(String[] args) {
32+
try {
33+
int arg = Integer.parseInt(args[0]);
34+
System.out.println(new Fibonacci().findNthElement(arg));
35+
} catch (Exception e) {
36+
System.out.println("The argument entered is not a valid integer number.");
37+
}
38+
}
39+
}

0 commit comments

Comments
 (0)