#LeetCode匠#爬楼梯

115 阅读1分钟

「这是我参与11月更文挑战的第4天,活动详情查看:2021最后一次更文挑战」。

我们今天一起体会下爬楼梯的乐趣

题目描述

假设你正在爬楼梯。需要 n 阶你才能到达楼顶。

每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?

注意:给定 n 是一个正整数。

题目示例

题目解法

解法一:动态规划

时间复杂度和空间复杂度均为O(n)。

/**
 * 动态规划-数组实现
 */
class Solution {
    public int climbStairs(int n) {
        // 1,2为边界值
        if(n <= 2){
            return n;
        }
        int[] stairs = new int[n+1];
        stairs[0] = 0;
        stairs[1] = 1;
        stairs[2] = 2;  //做铺垫,给3用
        for (int i = 3; i < n+1; i++) {
            stairs[i] = stairs[i-1] + stairs[i-2];
        }
        return stairs[n];
    }
}

解法二:指针遍历

时间复杂度和空间复杂度为O(n)

/**
 * 指针遍历
 */
class Solution {
    public int climbStairs(int n) {
        if(n <= 2){
            return n;
        }
        // n = n-1 + n-2
        // 以n-1和n-2为指针
        int pre1 = 1;
        int pre2 = 2;
        int nextNum = 0;
        while(n-- > 2){
            nextNum = pre1 + pre2;
            pre1 = pre2;
            pre2 = nextNum;
        }
        return nextNum;
    }
}

LeetCode原题链接:leetcode-cn.com/problems/cl…