|
| 1 | +package chapter08RecursionAndDynamicProgramming; |
| 2 | + |
| 3 | +/** |
| 4 | + * |
| 5 | + * Problem: Compute the Nth Fibonacci number. |
| 6 | + * |
| 7 | + */ |
| 8 | +public class Fibonacci { |
| 9 | + /** |
| 10 | + * Method 1: Recursive |
| 11 | + * |
| 12 | + * Time Complexity: O(2N), where N is the number of nodes. |
| 13 | + */ |
| 14 | + public int fibonacci1(int n) { |
| 15 | + if (n == 0 || n == 1) { |
| 16 | + return n; |
| 17 | + } |
| 18 | + return fibonacci1(n - 1) + fibonacci1(n - 2); |
| 19 | + } |
| 20 | + |
| 21 | + /** |
| 22 | + * Method 2: Top-Down Dynamic Programming (or Memorization) |
| 23 | + * |
| 24 | + * Time Complexity: O(N) |
| 25 | + */ |
| 26 | + public int fibonacci2(int n) { |
| 27 | + return helper(n, new int[n + 1]); |
| 28 | + } |
| 29 | + |
| 30 | + private int helper(int n, int[] memo) { |
| 31 | + if (n == 0 || n == 1) { |
| 32 | + return n; |
| 33 | + } |
| 34 | + if (memo[n] == 0) { |
| 35 | + memo[n] = helper(n - 1, memo) + helper(n - 2, memo); |
| 36 | + } |
| 37 | + return memo[n]; |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * Method 3: Bottom-Up Dynamic Programming |
| 42 | + */ |
| 43 | + public int fibonacci3(int n) { |
| 44 | + if (n == 0 || n == 1) { |
| 45 | + return n; |
| 46 | + } |
| 47 | + int[] memo = new int[n]; |
| 48 | + memo[0] = 0; |
| 49 | + memo[1] = 1; |
| 50 | + for (int i = 2; i < n; i++) { |
| 51 | + memo[i] = memo[i - 1] + memo[i - 2]; |
| 52 | + } |
| 53 | + return memo[n - 1] + memo[n - 2]; |
| 54 | + } |
| 55 | + |
| 56 | + /** |
| 57 | + * Method 4: Optimize Method3 |
| 58 | + */ |
| 59 | + public int fibonacci4(int n) { |
| 60 | + if (n == 0 || n == 1) { |
| 61 | + return n; |
| 62 | + } |
| 63 | + int a = 0; |
| 64 | + int b = 1; |
| 65 | + for (int i = 2; i < n; i++) { |
| 66 | + int c = a + b; |
| 67 | + a = b; |
| 68 | + b = c; |
| 69 | + } |
| 70 | + return a + b; |
| 71 | + } |
| 72 | +} |
0 commit comments