You are climbing a staircase. 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.

Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

这个题是一个典型的动态规划题。仔细思考会发现,从第三个台阶开始,对于任意一个台阶,只有两个路径可以一步到达,即跨一步或跨两步。而对于这个台阶来说,总共可以到达它的路径的数量就可以表示为它前面两个台阶的路径的和。想通了这一点,这个题就变成了一个斐波那契数列问题。

/*
 * 70. Climbing Stairs
 * https://leetcode.com/problems/climbing-stairs/
 * https://realneo.me/70-climbing-stairs/
 */

public class ClimbStairs {
    public static void main(String[] args) {
        ClimbStairs solution = new ClimbStairs();

        System.out.println(solution.climbStairs(5));
        System.out.println(solution.climbStairs(10));
    }

    private int climbStairs(int n) {
        if (n == 1) return 1;
        if (n == 2) return 2;

        int[] step = new int[n + 1];
        step[0] = 0;step[1] = 1;step[2] = 2;
        for (int i = 3; i <= n; i++)
            step[i] = step[i - 1] + step[i - 2];

        return step[n];
    }
}