BudiBadu Logo

Ways to Climb Stairs

Array Easy 4 views
Like7

You’re at the bottom of a staircase with n steps and want to be at the top. Each move covers either 1 or 2 steps. Your task in Ways to Climb Stairs is to find the total number of distinct move sequences that reach the top exactly. The order of steps matters: taking 1 then 2 is different from taking 2 then 1!

The "secret sauce" here is Iterative Accumulation (DP). To reach step i, your final move must have been either a 1-step from i-1 or a 2-step from i-2. This means the total ways to reach i is simply the sum of ways to reach those two prior positions. It's a classic pattern that solves the problem in O(n) time with minimal memory! Each pattern must add up exactly to n without overshooting. Mastering this logic lets you count billions of possible paths instantly, turning a complex combinatorial problem into a simple, professional routine for the dispatch team.

Examples

Example 1
Input
n = 3
Output
3
Explanation

The sequences are [1,1,1], [1,2], and [2,1].

Example 2
Input
n = 5
Output
8
Explanation

There are eight distinct sequences of 1s and 2s that sum to 5.

Example 3
Input
n = 1
Output
1
Explanation

Only one way — take a single step.

Algorithm Flow

Recommendation Algorithm Flow for Ways to Climb Stairs - Budibadu
Recommendation Algorithm Flow for Ways to Climb Stairs - Budibadu

Best Answers

java
class Solution {
    public int climb_stairs(Object n) {
        int num = (int) n;
        if (num <= 2) {
            return num;
        }
        int prev = 1;
        int curr = 2;
        for (int i = 3; i <= num; i++) {
            int next = prev + curr;
            prev = curr;
            curr = next;
        }
        return curr;
    }
}