LeetCode-70-Climbing stairs

Problem Description:
Suppose you are climbing stairs. It takes n steps for you to reach the top of the building.
You can climb 1 or 2 steps at a time. How many different ways can you climb to the top of a building?

Question link: LeetCode-70-Climbing stairs

Problem-solving ideas: Detailed explanations are provided in the comments.

Code:

class Solution {
    
    
    public int climbStairs(int n) {
    
    
        // 动规五部曲
        // 1. dp[i]: 走到第 i 阶有dp[i]种方法
        // 2. 递归公式:dp[i]=dp[i-1]+dp[i-2]  走到第3阶需要依赖第1个台阶走1步,第2个台阶走1步,和斐波那契数列一样
        // 3. 初始化:dp[0]=0; dp[1]=1 ; dp[2]=2
        // 4. 从前向后

        if (n==1){
    
    
            return 1;
        }
        if (n==2){
    
    
            return 2;
        }
        // 初始化
        int[] dp = new int[n+1];
        dp[0]=1;
        dp[1]=1;
        dp[2]=2;
        for (int i = 3; i <=n ; i++) {
    
    
            dp[i] = dp[i-1] + dp[i-2];
        }
        return dp[dp.length-1];
    }
}

Guess you like

Origin blog.csdn.net/Miss_croal/article/details/132854960