LeetCode 70. Climbing Stairs斐波那契系列问题解析

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Note: Given n will be a positive integer.

Example 1:

Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2:

Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

看到这个题,首先一阵窃喜,二话不说直接写出了递归版本进行submit:

class Solution {
    public int climbStairs(int n) {
        if(n <= 2){
            return n;
        }
        return climbStairs(n-1) + climbStairs(n-2);
    }
}

然而只得到了Time Limit Exceeded:

分析:递归的方法是有严重的效率问题。以求解f(10)为例,需要先求f(9)和f(8),然后相加。要求f(9),需要先求f(8)和f(7)......不难发现在计算的过程中,有许多重复的计算过程,而且重复的运算会随着n的增大而急剧增加。实际上,用递归方法计算的时间复杂度是以n的指数的方式递增的。

改进:避免重复的运算。可以从左到右依次求出每一项的值,通过顺序计算求到第n项即可。显然,这种解法的时间复杂度是O(n),可以通过所有的测试用例。

class Solution {
    public int climbStairs(int n) {
        if(n <= 2) return n;
        int preOneStep = 2;
        int preTwoStep = 1;
        int res = 0;
        for(int i=3;i<=n;i++){
            res = preOneStep + preTwoStep;
            preTwoStep = preOneStep;
            preOneStep = res;
        }
        return res;
    }
}

这个问题其实考察的是斐波那契数列,只是初始项稍有不同。

数列:0,1,1,2,3,5,8,13,21,34,55,89, ··· 是在13世纪由数学家斐波那契发现的,因此被命名为斐波那契数列。

斐波那契数列解法也还有另外几种O(logn)的解法:矩阵乘法、公式法。算法较为复杂,在这里不深入分析。

解决斐波那契数列相关的问题,关键是要找到递归公式,特别注意初始项。

斐波那契数列的问题还有许多,多多练习,做到灵活应用。例如:

①不断繁殖的动物:有一种读物,出生2天后就开始以每天1只的速度繁殖后代。假设第1天,有1只这样的动物(该动物刚出生,从第三天起繁殖后代)。到第11天,共有多少只?

②摆砖头:现要将1×2大小的砖头摆放成长方形阵列。并规定长方形的纵长必须是2.假设长方形的横长为n,运用斐波那契数列则砖头的摆法为F(n+1)。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

James Shangguan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值