Climbing Stairs(70)

Climbing Stairs

You are climbing a stair case. It takes n steps to reach to the top.code

Each time you can either climb 1 or 2 steps. In how many distinct ways
can you climb to the top?it

思路: 由于一次只能迈一个台阶或者两个台阶, 那么一个台阶只能由它上一个台阶或者上上一个台阶迈上来。 因此若是f(x) 表明方案数, 那么f(x) = f(x - 1) + f(x - 2); 获得了递推关系。 base状况时f(0) = 0, f(1)= 1, f(2) = 2(由于迈上第二层有两种方案, 一种是一次迈两步, 另外一种是一步一步的迈上去)。 io

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

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];
        
    }
}
相关文章
相关标签/搜索