本题可以提供一个时间复杂度为O(1)的解法。
就是直接求出通项公式,用高中数列特征根的方法(不会网上查)
下面是代码
class Solution {
public:
int Fibonacci(int n) {
return (1.0 / sqrt(5)) * (pow((1 + sqrt(5)) / 2, n) - pow((1 - sqrt(5)) / 2, n));
}
};

京公网安备 11010502036488号