LeetCode 509. 斐波那契数
题目描述
LeetCode页面
方法一:常规方法
class Solution {
public int fib(int n) {
int res = 0;
if (n < 2) {
res = n;
} else {
res = fib(n - 1) + fib(n - 2);
}
return res;
}
}
方法二:滚动数组
参考于LeetCode官方题解
class Solution3 {
public int fib(int n) {
if (n < 2) {
return n;
}
int p = 0, q = 0, r = 1;
for (int i = 2; i <= n; i++) {
p = q;
q = r;
r = q + r;
}
return r;
}
}
方法三:通式法
public int fib(int n) {
double sqrt_5 = Math.sqrt(5);
double fibN = Math.pow((1 + sqrt_5) / 2 - (1 - sqrt_5 / 2), n);
return (int) Math.round(fibN / sqrt_5);
}
参考于LeetCode官方题解