@@ -22,6 +22,7 @@ public FibonacciNumber(int n)
2222
2323 private int fib ( int n )
2424 {
25+ /*
2526 // Base cases
2627 int result = 0;
2728 if (n == 0) return result;
@@ -35,12 +36,53 @@ private int fib(int n)
3536 result = fib(n - 1) + fib(n - 2);
3637 }
3738 return result;
39+ */
40+ int ? [ ] memo = new int ? [ n + 1 ] ;
41+ return fibMemoization ( n , memo ) ;
42+ }
43+
44+ // Using Memoization to cache Fibonacci results
45+ // Improves Time Complexity from O(2^n) to O(n)
46+ private int fibMemoization ( int n , int ? [ ] memo )
47+ {
48+ // If the result has already been calculated, it will exist in the memo array.
49+ if ( memo [ n ] != null ) return ( int ) memo [ n ] ;
50+ int result = 0 ;
51+ if ( n == 0 ) return result ;
52+ if ( n == 1 || n == 2 )
53+ {
54+ result = 1 ;
55+ }
56+ else
57+ {
58+ result = fib ( n - 1 ) + fib ( n - 2 ) ;
59+ memo [ n ] = result ;
60+ }
61+ return result ;
62+ }
63+
64+ private int fibBottomUp ( int n )
65+ {
66+ // Time Complexity : O(n)
67+ // Space Complexity: O(n), where n is the input number
68+ // Base Cases
69+ if ( n == 0 ) return 0 ;
70+ if ( n == 1 || n == 2 ) return 1 ;
71+ // Build the Fibonacci Sequence from left to right iteratively
72+ int [ ] bottomUp = new int [ n + 1 ] ;
73+ bottomUp [ 1 ] = 1 ;
74+ bottomUp [ 2 ] = 1 ;
75+ for ( int i = 3 ; i < bottomUp . Length ; i ++ )
76+ {
77+ bottomUp [ i ] = bottomUp [ i - 1 ] + bottomUp [ i - 2 ] ;
78+ }
79+ return bottomUp [ n ] ;
3880 }
3981
4082 public override void PrintExample ( )
4183 {
4284 var watch = System . Diagnostics . Stopwatch . StartNew ( ) ;
43- var results = fib ( this . n ) ;
85+ var results = fibBottomUp ( this . n ) ;
4486 watch . Stop ( ) ;
4587 Console . WriteLine ( $ "509. Fibonacci Number\n " +
4688 $ "Input Num = { this . n } \n " +
0 commit comments