使用 记忆化 技巧 解决 递归产生的重复计算问题。
记忆化:在相同的输入再次出现时返回缓存的结果。
使用散列表(哈希表)缓存输入的结果。
java的HashMap提供containsKey() 判断输入是否存在缓存。使用get() 获取缓存值。put()添加缓存。
class Solution {
HashMap<Integer,Integer> cache = new HashMap<>();
public int fib(int n) {
if(cache.containsKey(n)){
return cache.get(n);
}
int res;
if(n<2){
res = n;
}else{
res = fib(n-2) + fib(n-1);
}
cache.put(n,res);
return res;
}
}
爬楼梯也是 斐波那契的变形,不同在于 n=2时,res也是等于其本身。
class Solution {
HashMap<Integer,Integer> cache = new HashMap<>();
public int climbStairs(int n) {
if(cache.containsKey(n)){
return cache.get(n);
}
int res;
if(n<=2){
res = n;
}else{
res = climbStairs(n-2) + climbStairs(n-1);
}
cache.put(n,res);
return res;
}
}