I have a quick question about implementing the Fibonacci sequence using the memoization (DP). I am using a HashTable, but for some reason, the table never seems to contain the elements. I inserted a print statement to print out something whenever a value was read from the hashtable and it seems like this never happens. I feel like its a simple fix, but I don't see it.
public static int getFib(int n) {
HashMap<Integer, Integer> dictionary = new HashMap<Integer, Integer>();
if (n <= 2)
return 1;
else if (dictionary.containsKey(n)) {
System.out.println("Reading From Table");
return dictionary.get(n);
} else {
int val = getFib(n - 1) + getFib(n - 2);
dictionary.put(n, val);
return val;
}
}
result = dictionary.get(n); if (null != result) …