use*_*234 1 java algorithm dynamic-programming fibonacci
我有一个关于使用memoization(DP)实现Fibonacci序列的快速问题.我正在使用HashTable,但由于某种原因,该表似乎永远不会包含这些元素.我插入一个print语句,以便在从哈希表中读取值时打印出来,似乎这种情况从未发生过.我觉得这是一个简单的修复,但我没有看到它.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
194 次 |
| 最近记录: |