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.

RustData Integrity

Code

rustsnippet
16 lines
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

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(`.