Topic describes

Their thinking

  • In this case, if you use recursion to calculate directly, the idea is simple, but it will surely time out, because the time complexity of recursion is too high, so this case uses the circular calculation method.
  • The so-called loop method uses two temporary variables to refer to the first two elements of the ith element, which are updated as I is updated.

The problem solving code

var fib = function(n) {
    if (n <= 1) return n;
    let temp1 = 1;
    let temp2 = 1;
    let res;
    for (let i = 0 ; i < n; i++) {
        res = temp1;
        temp1 = temp2;
        temp2 = (res + temp1) % 1000000007
    }
    return res;
};
Copy the code

Conclusion (this topic gives us the enlightenment of thinking)

  • Learn to solve recursion problems such as Fibonacci sequence through cyclic calculation.