0070. Climbing Stairs (E)

Climbing Stairs (E)

题目

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层,统计可以登顶的方法的个数。

思路

动态规划:dp[i]代表能够走到第i层的方法的个数,而第i层只可能由第i-1层走1层到达,或由第i-2层走2层到达,所以有 \(dp[i]=dp[i-1]+dp[i-2]\)

递归:从当前层i走到最高层的方法数等于从i+1层走到最高层的方法数加上i+2层走到最高层的方法数。


代码实现

Java

动态规划

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

递归

class Solution {
    public int climbStairs(int n) {
        int[] ways = new int[n + 1];	// 避免重复运算
        return findWays(0, n, ways);
    }

    // 返回从第i层走到第n层的方法数
    private int findWays(int i, int n, int[] ways) {
        if (i == n) {
            return 1;
        }
        if (i > n) {
            return 0;
        }
        
        if (ways[i] > 0) {
            return ways[i];
        }
        
        ways[i] = findWays(i + 1, n, ways) + findWays(i + 2, n, ways);
        return ways[i];
    }
}

JavaScript

/**
 * @param {number} n
 * @return {number}
 */
var climbStairs = function (n) {
  let dp = [1, 2]
  for (let i = 2; i < n; i++) {
    dp[i] = dp[i - 2] + dp[i - 1]
  }

  return dp[n - 1]
}
posted @ 2020-08-01 09:57  墨云黑  阅读(186)  评论(0编辑  收藏  举报