爬台阶问题(每一次爬一阶台阶,或者每一次爬二阶台阶)

package leetcode;
/*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接台阶,能够理解为最后一次是爬一个台阶,那么前面就是n-1阶台阶有多少种爬法.最后一次爬两个台阶,那么前面就是n-2种爬法code

public class Climbing_stairs {
     public static void main(String[] args) {
        System.out.println(climbStairs(3));
    }
     
     public static int climbStairs(int n) {
         if(n == 0)
             return 0;
         if(n == 1)
             return 1;
        int[] a = new int[n+1];     //定义了数组存储以前计算过的结果
        a[0] = 1;                     
        a[1] = 1;           //这么初始化的缘由是,两个台阶能够理解为第一次爬一个台阶,和第一次一个台阶都不怕
                            //也能够选择初始化a[1]和a[2]
        for(int i = 2 ; i <= n ; i ++ ) {
                a[i] = a[i-1]+a[i-2];         
            }
        return a[n];
     }
}
 递归