[LintCode]Fibonacci
class Solution {
/**
* @param n: an integer
* @return an integer f(n)
*/
HashMap<Integer, Integer> map;
public int fibonacci(int n) {
// 2015-07-16
// 用哈希表提高时间效率,算过的值就保存下来,不用再算
// 注意递归要向“已知”的方向
if (map == null) {
map = new HashMap<>();
}
if (n <= 0) {
return -1;
} else if (n == 1) {
return 0;
} else if (n == 2) {
return 1;
} else {
if (!map.containsKey(n - 1)) {
map.put(n - 1, fibonacci(n - 1));
}
if (!map.containsKey(n - 2)) {
map.put(n - 2, fibonacci(n - 2));
}
return map.get(n - 1) + map.get(n - 2);
}
}
}