美文网首页
111.爬楼梯

111.爬楼梯

作者: 哲哲哥 | 来源:发表于2017-10-22 12:05 被阅读0次

    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?

    比如n=3,1+1+1=1+2=2+1=3,共有3中不同的方法

    登上第1级:1种
    登上第2级:2种
    登上第3级:1+2=3种(前一步要么从第1级迈上来,要么从第2级迈上来)
    登上第4级:2+3=5种(前一步要么从第2级迈上来,要么从第3级迈上来)
    登上第5级:3+5=8种
    登上第6级:5+8=13种
    登上第7级:8+13=21种
    登上第8级:13+21=34种
    登上第9级:21+34=55种
    登上第10级:34+55=89种.

    f(n)=f(n-1)+f(n-2);
    这有一点像斐波那契数列

    斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368。
    这个数列从第3项开始,每一项都等于前两项之和。

    但是n=1时f(n)=1,n=2时f(n)=2

    public int climbStairs(int n) {
           
          int re = 0;
            if(n == 0 || n == 1){
                return 1;
            }else{
                re = climbStairs(n-1)+climbStairs(n-2);
            }
            return re;
        }
    

    这样是会超时的

    相关文章

      网友评论

          本文标题:111.爬楼梯

          本文链接:https://www.haomeiwen.com/subject/cxyguxtx.html