import java.util.Map; import java.util.HashMap; class MapExample { /////////////////////////////////////////////////////////////////////////////////// /* Computes the nth fibonacci number using bottom-up Dynamic Programming. */ static long dpfib(int n) { if (n < 2) return n; long[] table = new long[n+1]; table[0] = 0; table[1] = 1; for (int i = 2; i <= n; i++) table[i] = table[i-1] + table[i-2]; return table[n]; } /////////////////////////////////////////////////////////////////////////////////// /* Precondition: n >= 0 * Computes the nth fibonacci number using Memoization. */ static long mpfib(int n) { Map table = new HashMap(); // Computes f(n) using the recurrence & the table. return memoize(n, table); } /* Precondition: n >= 0 */ static long memoize(int n, Map table) { Long val = table.get(n); if (val == null) { if (n < 2) { table.put(n, (long)n); } else { table.put(n, memoize(n-1, table) + memoize(n-2, table)); } } return table.get(n); } public static void main(String[] args) { for (int n = 0; n < 20; n++) { System.out.printf("dpfib(%d) = %d, ", n, dpfib(n)); System.out.printf("mpfib(%d) = %d%n", n, mpfib(n)); } } }