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?
Given n will be a positive integer.
Example:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Write your solution:
Test Case 1
Input: 2
Output: 2
Test Case 2
Input: 3
Output: 3
Test Case 3
Input: 4
Output: 5
Test Case 4
Input: 13
Output: 377
Solution
Complexity:
- Time complexity: O(n)
- Space complexity: O(1)
function climbStairs(n) {
let a = 0,
b = 1;
for (let i = 0; i < n; i++) {
[a, b] = [b, a + b];
}
return b;
}