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?

分析:

一共有n个台阶,可以一次走一步,也可以一次走两步,有多少种不同的走法?

这道题类似于小机器人找unique path的题,

对于某级台阶i,有两种可能到达它,一种可能是从它前一级台阶,也有一种可能是从它前一级的前一级,

所以我们得到了最优解的公式:ways[i] = ways[i-1] + ways[i-2];

当然,我们还要给出初始条件, ways[0]=1, ways[1]=2。

第一级台阶我们只有一种方式走到它,但是对于第二级台阶有可能是一级一级走上来的,也可能从跨了两级走上来的。

有点类似于斐波纳切数列呢~

public class Solution {
    public int climbStairs(int n) {
        if (n <= 1){
            return n;  
        }
        int[] ways = new int[n];
        ways[0] = 1;
        ways[1] = 2;
        
        for (int i = 2; i < n; i++){
            ways[i] = ways[i-1] + ways[i-2];
        }
        return ways[n-1];
    }
}
原文地址:https://www.cnblogs.com/iwangzheng/p/5728844.html