|
| 1 | +import '../utils/time_measure.dart'; |
| 2 | + |
| 3 | +/// Calculate fibonacci number at specific position "n" using Dynamic Programming approach. |
| 4 | +/// Fibonacci Sequence: |
| 5 | +/// 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 |
| 6 | +void main() { |
| 7 | + syncExecTimeMeasure(() => print(fibTabulated(45)), name: 'O(n)'); |
| 8 | + syncExecTimeMeasure(() => print(fibMemoized(45)), name: 'O(n)'); |
| 9 | + syncExecTimeMeasure(() => print(fibRecursive(45)), name: 'O(n^2)'); |
| 10 | +} |
| 11 | + |
| 12 | +// Tabulation (Bottom-up approach in Dynamic Programming) |
| 13 | +// Time Complexity: O(n), and better Auxiliary Space. |
| 14 | +fibTabulated(int n) { |
| 15 | + if (n <= 0) throw ArgumentError('Input must be a positive integer'); |
| 16 | + |
| 17 | + final table = [1, 1]; |
| 18 | + int currentFib = 1; |
| 19 | + |
| 20 | + for (int i = 3; i <= n; i++) { |
| 21 | + currentFib = table[0] + table[1]; |
| 22 | + table[0] = table[1]; |
| 23 | + table[1] = currentFib; |
| 24 | + } |
| 25 | + return currentFib; |
| 26 | +} |
| 27 | + |
| 28 | +// Memoization (Top-down approach in Dynamic Programming) (involves recursion). |
| 29 | +// Time Complexity: O(n) |
| 30 | +fibMemoized(int n) { |
| 31 | + if (n <= 0) throw ArgumentError('Input must be a positive integer'); |
| 32 | + if (n <= 2) return 1; |
| 33 | + if (_memo.containsKey(n)) return _memo[n]; |
| 34 | + |
| 35 | + final result = fibMemoized(n - 1) + fibMemoized(n - 2); |
| 36 | + _memo[n] = result; |
| 37 | + return result; |
| 38 | +} |
| 39 | + |
| 40 | +final Map<int, int> _memo = {}; |
| 41 | + |
| 42 | +// Naive solution using Recursion. |
| 43 | +// Time Complexity: O(2^n) "Exponential Big O" |
| 44 | +// https://i.stack.imgur.com/kgXDS.png |
| 45 | +// Note: it's exactly (1.6180339887^n), which is known as the golden ratio: |
| 46 | +// https://stackoverflow.com/questions/360748 |
| 47 | +fibRecursive(int n) { |
| 48 | + if (n <= 0) throw ArgumentError('Input must be a positive integer'); |
| 49 | + if (n <= 2) return 1; |
| 50 | + |
| 51 | + return fibRecursive(n - 1) + fibRecursive(n - 2); |
| 52 | +} |
0 commit comments