【LeetCode】 70. Climbing Stairs 爬楼梯(Easy)(JAVA)

【LeetCode】 70. Climbing Stairs 爬楼梯(Easy)(JAVA)

题目地址: https://leetcode.com/problems/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?

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

题目大意

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

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

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

解题方法

1、找出动态规划 dp 公式 dp[n] = dp[n - 2] + dp[n - 1]; dp[2] = 2, dp[1] = 1
2、简化 dp 公式,因为只用到的 dp[n - 1] 和 dp[n - 2],用两个变量替代即可

class Solution {
    public int climbStairs(int n) {
        if (n <= 2) return n;
        int pre = 1;
        int cur = 2;
        for (int i = 3; i <= n; i++) {
            int temp = cur;
            cur += pre;
            pre = temp;
        }
        return cur;
    }
}

执行用时 : 0 ms, 在所有 Java 提交中击败了 100.00% 的用户
内存消耗 : 36.6 MB, 在所有 Java 提交中击败了 5.07% 的用户

发布了95 篇原创文章 · 获赞 6 · 访问量 2810

猜你喜欢

转载自blog.csdn.net/qq_16927853/article/details/104916527