算法小白学斐波那契数列,懵圈

78 阅读1分钟

今天学习了个斐波那契数列怎么倒推,结果死活卡在循环关键点。 老师给的倒推方法如下:

    function fib (n) {
        if (n < 2) {
            return n
        } else {
            let pre = 0, next = 0, result = 1
            for (let i=2; i<n; i++) {
            // 这里的写法顺着读让我很不明白?
                pre = next
                next = result
                result = pre + next 
                // 0,1,1,2,3,
            // 那倒过来解读试试()
            // => 已知 result = pre + next
            // => next = 已经出来的result
            // => pre = next
            }
            return result
        }
    }

为啥理解pre=next; next=result;这里对我来说这么难呢? 搞不懂啊。

接下来又有个输出斐波那契数列的方法,因为对n的理解有误,又把自己整懵了。 for 循环那里的 习惯性写的是i<n,写完后执行outputFib(2) 总是[0, 1],i 也只打印到1,但不知道n是index前并不知道自己哪写错了。 n是下标数index,index是从0开始,所以outputFib(2)的数列应该是3个,那么i <= n 才能符合这个需求。

     function outputFib (n) {
        let list = []
        let a1 = 0, a2 = 0, result = 1
        for (let i=0; i<=n; i++) {
            if (i < 2) {
                list.push(i)
            } else {
                a1 = a2
                a2 = result
                result = a1 + a2
                list.push(result)
            }
        }
        return list
    }