#70
Easy Algorithms Climbing stairs
Math Dynamic Programming Memoization
53.9% acceptance
Jan 12, 2026
24327
1039
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?
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn climb_stairs(n: i32) -> i32 {
if n <= 2 {
return n;
}
let mut prev2 = 1;
let mut prev1 = 2;
for _ in 3..=n {
let curr = prev1 + prev2;
prev2 = prev1;
prev1 = curr;
}
prev1
}
}