File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed
Leetcode/leetcodeTags/array Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change 1+ package leetcodeTags .array ;
2+
3+ import java .util .Arrays ;
4+
5+ public class FibonacciNumber509 {
6+
7+ // using recursion
8+ public static int fib (int n ) {
9+ if (n == 0 || n == 1 )
10+ return n ;
11+
12+ int fibonacci = fib (n - 1 ) + fib (n - 2 );
13+ return fibonacci ;
14+ }
15+
16+ // using DP
17+ public static int fibDP (int n ) {
18+ if (n == 0 || n == 1 )
19+ return n ;
20+
21+ int [] storage = new int [n + 1 ];
22+ Arrays .fill (storage , -1 ); // initializing DP array with -1
23+
24+ // filling first two positions
25+ storage [0 ] = 0 ;
26+ storage [1 ] = 1 ;
27+
28+ return fibTopDown (n , storage );
29+ }
30+
31+ private static int fibTopDown (int n , int [] storage ) {
32+ if (n == 0 || n == 1 )
33+ return n ;
34+
35+ if (storage [n ] != -1 )
36+ return storage [n ];
37+
38+ int fibonacci = fibTopDown (n - 1 , storage ) + fibTopDown (n - 2 , storage );
39+ storage [n ] = fibonacci ;
40+
41+ return fibonacci ;
42+ }
43+
44+ public static void main (String [] args ) {
45+ for (int i = 0 ; i <= 7 ; i ++) {
46+ System .out .println (fib (i ));
47+ }
48+
49+ System .out .println ("\n testing DP code\n " );
50+ for (int i = 0 ; i <= 7 ; i ++) {
51+ System .out .println (fibDP (i ));
52+ }
53+ }
54+ }
You can’t perform that action at this time.
0 commit comments