zoukankan      html  css  js  c++  java
  • 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.

    有n阶楼梯,一次可以上一阶、也可以上2阶,求总共有多少种不同的走法

    这是斐波那契数列问题,其中一个有名的问题:兔子繁殖。如下图,

    按照上面的思路,给出代码:

    public int climbStairs(int n) {
            if(n <= 0 ) return 0;
            if(n == 1) return 1;
            if(n == 2) return 2;
            int sum = 0;
            int n_2 = 1; //A(n-2)=1
            int n_1 = 2;  // n-1=2
            for(int i = 2; i < n; i++)
            {
                sum = n_1 + n_2;
                n_2 = n_1;
                n_1 = sum;
            }
            return sum;
        }
    

    每一阶段有多少中走法,可以使用一个数组记录下来

    先初始化要给全为0的数组

    
    int a[] = new int[n]; //n阶楼梯,eg,a[4]表示5阶楼梯的走法
    
    public static int climbStairs(int a[],int m)
        {
            a[0] = 1;
            a[1] = 2;
            for(int i = 2;i <= m; i++)
                a[i] = a[i - 1] + a[i - 2];
            return a[m] ;
        }
    
  • 相关阅读:
    树的可视化
    图的可视化
    1+1=2
    用xapian来做索引
    学习的快乐
    项目小结
    z=sin(xy)
    Min Stack
    互联网公司的文化
    为什么要读数学书
  • 原文地址:https://www.cnblogs.com/wxshi/p/7783032.html
Copyright © 2011-2022 走看看