Climbing Stairs
EasyYou 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?
Examples
| Input | Output |
|---|---|
| n = 2 | 2 |
| n = 3 | 3 |
Python Solution
def climb_stairs(n: int) -> int:
if n <= 2:
return n
a, b = 1, 2
for _ in range(3, n + 1):
a, b = b, a + b
return bJavaScript Solution
function climbStairs(n) {
if (n <= 2) return n;
let a = 1, b = 2;
for (let i = 3; i <= n; i++) {
[a, b] = [b, a + b];
}
return b;
}Step-by-Step Explanation
- Same recurrence as Fibonacci: ways(n) = ways(n-1) + ways(n-2).
- Use iterative DP with two variables to avoid recursion.
Complexity Analysis
| Time | O(n) |
| Space | O(1) |
Tags
MathDynamic Programming
Related Problems
All Problems
Two SumReverse a StringPalindrome CheckFizzBuzzBinary SearchReverse Linked ListMerge Two Sorted ArraysValid ParenthesesMaximum Subarray (Kadane's Algorithm)Remove Duplicates from Sorted ArrayNth Fibonacci NumberValid AnagramFirst Unique CharacterRoman to IntegerBest Time to Buy and Sell StockContains DuplicateMove ZeroesIntersection of Two ArraysLongest Common Prefix