題目出處:https://leetcode.com/problems/climbing-stairs/
題目描述:
你正在爬樓梯。 它需要n步才能達到頂峰。
每次你可以爬1或2步。 您可以通過多少不同的方式登頂?注意:給定n将是一個正整數。
自己算幾遍就會發現,這是一個斐波那契額數列,輸入的n是數組中的元素下标,傳回值是array[n]
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
代碼:
//斐波那契數列
var climbStairs = function(n) {
//數組前2項
if (n<3) return n;
//計算數組第3項之後
let step_1 = 1;
let step_2 = 2;
for(var i = 2 ;i<n;i++){
let temp = step_2;
step_2 = step_1 + step_2;
step_1 = temp;
}
return step_2
}
leetcode記錄:難度簡單:70. Climbing Stairs
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnLzUzNwMTNwAjMzITMwkTMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
思路:
斐波那契額數列的求和有很多種方式,有尾遞歸優化的,也有其他的。選自己容易了解的。
因為本題目沒有要求把整個數列都求出來,是以我就循環求和了