70. Climbing Stairs - jiejackyzhang/leetcode-note GitHub Wiki

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?

解题思路为Dynamic Programming。 令P[n]表示到达n台阶的不同方法次数,则n台阶可由n-1台阶或n-2台阶到达,因此 P[n] = P[n-1]+P[n-2]

可见,这是一个斐波那契数列。

public class Solution {
    public int climbStairs(int n) {
        int a = 0, b = 1;
        for(int i = 0; i < n; i++) {
            b = a + b;
            a = b - a;
        }
        return b;
    }
}