70. Climbing Stairs
Posted songya
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了70. 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.
例1
Input: 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps
例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
解:用Dynamic Programming(动态规划)
思路:这个问题可以分解为子问题,并且它包含最优的子结构属性,即它的最优解可以从其子问题的最优解中构建,可以使用动态规划来解决这个问题。
到达第 i 步有两种方式:
1、从第 (i - 1)步中,爬一步到达;
2、从第(i - 2)步中,爬两步到达。
所以:到达第 i 步 = 到达第(i - 1)步 + 到达第(i-2)步
dp[i] = dp[i-1] + dp[i-2]
/** * @param {number} n * @return {number} */ var climbStairs = function(n) { if (n === 1) { return 1; } let dp = {}; dp[1] = 1; dp[2] = 2; for (var i = 3; i<=n; i++) { dp[i] = dp[i-1] + dp[i-2]; } return dp[n] };
复杂度分析:
时间复杂度:O(n)
空间复杂度:O(n)
(leetcode solution链接:https://leetcode.com/articles/climbing-stairs/)
以上是关于70. Climbing Stairs的主要内容,如果未能解决你的问题,请参考以下文章