LeetCode之爬梯子

来源:互联网 发布:以人为镜可以知得失矣 编辑:程序博客网 时间:2024/04/30 03:38

问题描述:

/** * 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阶梯子,每次只能爬1阶或者2阶,问爬到N阶时,可以有多少方式?
可以这样思考,爬到N阶,可以从第N-1阶爬1步,也可以从第N-2阶爬2步。也就是说到N阶的方式有f(N-1)+f(N-2)种方式(因为要么1步,要么2步),后面一次类推。可以看出这是个菲波那切数列。

public static int climbStairs(int n) {        int[] arr = new int[n + 1];        arr[0] = 1;        arr[1] = 1;        for (int i = 2; i <= n; i++) {            arr[i] = arr[i - 1] + arr[i - 2];        }        return arr[n];    }    //测试代码    public static void main(String args[])    {        int n=4;        System.out.print(climbStairs(n));    }
0 0
原创粉丝点击