Leetcode P0070"Climbing Stairs" 题解

2020/08/28 Leetcode

博文中会简要介绍Leetcode P0070题目分析及解题思路。

“Climbing Stairs”是很经典的动态规划问题,很多动态规划问题的原型都是这道题,例如p0062和p0063。这道题相对简单,递推表达式也比较容易想到。

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?

这道题的递推式如下:

    令dp[i]是爬到第i个台阶的不同方法的个数

    dp[0] = 1
    dp[1] = 1
    显然只有一个台阶的时候只有一种走法

    dp[i] = dp[i-1]+dp[i-2]
    相当于走一步或者走两步的全部走法相加

以下是Java的题解代码实现。

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

以下是C++的题解代码实现。

class Solution {
public:
    int climbStairs(int n) {
        if (n == 1)
            return 1;
        
        int *dp = new int[n+1];
        dp[0] = 1;
        dp[1] = 1;
        
        for (int i1=2; i1<=n; ++i1) {
            dp[i1] = dp[i1-1]+dp[i1-2];
        }
        
        return dp[n];
    }
};

Search

    Table of Contents