爬楼梯
Climbing Stairs
题目详情
问题:爬楼梯
考察:动态规划
来源:Citadel
链接:https://www.jointaro.com/interviews/questions/climbing-stairs/
You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Example 1:
Input: n = 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps
Example 2:
Input: n = 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
Constraints:
1 <= n <= 45
解析
思路:到第 i 阶只可能来自第 i-1 阶或第 i-2 阶,因此是斐波那契递推。滚动保存前两项即可。
复杂度:时间 O(n),空间 O(1)。