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?

思路: 因为一次只能迈一个台阶或者两个台阶, 那么一个台阶只能由它上一个台阶或者上上一个台阶迈上来。 所以如果f(x) 代表方案数, 那么f(x) = f(x - 1) + f(x - 2); 得到了递推关系。 base情况时f(0) = 0, f(1)= 1, f(2) = 2(因为迈上第二层有两种方案, 一种是一次迈两步, 另一种是一步一步的迈上去)。

时间复杂度:O(n)
空间复杂度:O(n)

public class Solution {
    public int climbStairs(int n) {
       
        if (n <= 2) {
            return n;
        }
        int[] f = new int[n + 1];
        f[0] = 0;
        f[1] = 1;
        f[2] = 2;
        
        for (int i = 3; i <= n; i++) {
            f[i] = f[i - 1] + f[i - 2];
        }
        return f[n];
        
    }
}

colorfuladventure
4 声望4 粉丝

引用和评论

0 条评论