斐波那契数列

题目: 70. 爬楼梯

记忆化搜索

func climbStairs(n int) int {
    cache := []int{1, 1}
    var fib func(x int) int
    fib = func(x int) int {
        if x < len(cache) {
            return cache[x]
        }
        cache = append(cache, fib(x - 1) + fib(x - 2))
        return cache[x]
    }
    return fib(n)
}

如果只用一次, 也可以不留结果

func climbStairs(n int) int {
    i, j := 1, 1
    for t := 0; t < n; t++ {
        i, j = j, i + j
    }
    return i
}

这两个方法时间复杂度都是 \(O(n)\), 有趣的是题解里给了个解析解:

齐次线性递推 \(f(n)=f(n-1)+f(n-2)\) 有特征方程 \(x^2=x+1\), 求得 \(x_1=\frac{1+\sqrt{5}}{2}\), \(x_2=\frac{1-\sqrt{5}}{2}\).

我没学过这个东西, 在我的理解中, 特征方程的x是一次线性变换 \(g(x)\), 原本的递推方程可以表示为 \(g^2(x)=g(x)+x\),

进一步地, 由于有两个根, \(g(x)\) 可能是 \(x_1\)\(x_2\) 组成的线性变换, 因此可设 \(g(x)=c_1x_1+c_2x_2\).

设通解为 \(f(n)=c_1x_1^n+c_2x_2^n\), 代入初始条件 \(f(1)=1\), \(f(2)=1\), 得 \(c_1=\frac{1}{\sqrt{5}}\), \(c_2=-\frac{1}{\sqrt{5}}\).

所以 \(f(n)=\frac{1}{\sqrt{5}}[(\frac{1+\sqrt{5}}{2})^n-(\frac{1-\sqrt{5}}{2})^n]\)

如果希望n和题目一致, 可以代入 \(f(1)=1\), \(f(2)=2\), 得 \(c_1=\frac{\sqrt{5}+1}{2\sqrt{5}}\), \(c_2=\frac{\sqrt{5}-1}{2\sqrt{5}}\), 后面一样.

看到漫士老师的这个视频, 解释的很简单.

posted @ 2025-03-12 01:16  aparaburu  阅读(25)  评论(0)    收藏  举报