题目描述
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0,第1项是1)。
n\leq 39n≤39
public int fib(int n) {
int a = 0;
int b = 1;
int sum = 0;
for (int i = 0; i < n; i++) {
sum = (a+b)%1000000007;
a = b;
b = sum;
}
return a;
}
int constant = 1000000007;
public int fib(int n) {
return fib(n, new HashMap());
}
public int fib(int n, Map<Integer, Integer> map) {
if (n < 2)
return n;
if (map.containsKey(n))
return map.get(n);
int first = fib(n - 1, map) % constant;
map.put(n - 1, first);
int second = fib(n - 2, map) % constant;
map.put(n - 2, second);
int res = (first + second) % constant;
map.put(n, res);
return res;
}
public int Fibonacci(int n) {
if (n < 2){
return n;
}
return Fibonacci(n-1)+Fibonacci(n-2);
}