[LeetCode] 70. Climbing Stairs
Posted aaronliu1991
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 70. Climbing Stairs相关的知识,希望对你有一定的参考价值。
爬楼梯。题意是给一个数字n代表楼梯的高度,你可以每次爬一步或者两步,求有多少种不同的爬法。例子,
Example 1:
Input: 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 stepsExample 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
我看了好几个discussion,才发觉这个题本质上是斐波那契数列。当输入为1, 2, 3, 4, 5, 6, 7, 8, 9, 10时,观察输出为1, 2, 3, 5, 8, 13, 21, 34, 55, 89。所以做法就很直观了。
迭代
时间O(n)
空间O(n)
1 /** 2 * @param {number} n 3 * @return {number} 4 */ 5 var climbStairs = function (n) { 6 const climing = []; 7 // using variables because they allocate a memory only once 8 let minusTwoSteps = 1; 9 if (n === 1) { 10 return 1; 11 } 12 let minusOneStep = 2; 13 if (n === 2) { 14 return 2; 15 } 16 let current = 0; 17 for (let i = 3; i <= n; i++) { 18 current = minusTwoSteps + minusOneStep; // current step - is a sum of two previous ones 19 minusTwoSteps = minusOneStep; // -2 steps for next iteration would be current - first 20 minusOneStep = current; // -1 step for next iteration would be our current 21 } 22 return current; 23 };
DP
时间O(n)
空间O(n)
1 /** 2 * @param {number} n 3 * @return {number} 4 */ 5 var climbStairs = function (n) { 6 if (n === 0) return 0; 7 let dp = [n + 1]; 8 dp[0] = 1; 9 dp[1] = 1; 10 for (let i = 2; i <= n; i++) { 11 dp[i] = dp[i - 1] + dp[i - 2]; 12 } 13 return dp[n]; 14 };
以上是关于[LeetCode] 70. Climbing Stairs的主要内容,如果未能解决你的问题,请参考以下文章