Climbing Stairs With Bottom Up DP
Fill the recurrence ways(n) = ways(n-1) + ways(n-2) with two rolling variables, so each step count needs only one pass and O(1) memory.
Code
fn climb_stairs(n: usize) -> u64 {
// bottom-up DP: ways(n) = ways(n-1) + ways(n-2)
let (mut a, mut b) = (1u64, 1u64);
for _ in 2..=n {
let next = a + b;
a = b;
b = next;
}
b
}
fn main() {
for n in [1, 2, 3, 5, 10, 20] {
println!("climb_stairs({n}) = {}", climb_stairs(n));
}
}Line-by-line reading
Climbing Stairs With Bottom Up DP is built around the functions climb_stairs and main.
for _ in 2..=n carries the work item by item.
Watch out for
- The whole dependency story is the language version itself.
Using it
The entry-point signature is fn climb_stairs(n: usize) -> u64
Output lines are prefixed (climb_stairs(), so the effect of each step announces itself.
main sequences climb_stairs; executing the file runs that flow once.
Key statements
fn climb_stairs(n: usize) -> u64 {
// bottom-up DP: ways(n) = ways(n-1) + ways(n-2)
let (mut a, mut b) = (1u64, 1u64);
for _ in 2..=n {
let next = a + b;
a = b;
b = next;
}
b
}
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Climbing Stairs With Bottom Up DP print when run?
- Running the file directly is enough — expect labeled output lines such as `climb_stairs(`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.