使用循环
class Solution {
public int fib(int n) {
if(n == 0){
return 0;
}
if(n == 1){
return 1;
}
int res = 0;
int pre1 = 1;
int pre2 = 0;
for(int i = 2; i <= n; i++){
res = pre1 + pre2;
pre2 = pre1;
pre1 = res;
}
return res;
}
}
使用HashMap
class Solution {
private Map<Integer,Integer> storeMap = new HashMap();
public int fib(int n) {
if(n == 0){
return 0;
}
if(n == 1){
return 1;
}
if(null != storeMap.get(n)){
return storeMap.get(n);
}else{
int res = fib(n-1) + fib(n-2);
storeMap.put(n,res);
return res;
}
}
}