Start learning free

LESSON 238 OF 314 · DYNAMIC PROGRAMMING

Climbing Stairs in C++: Dynamic Programming with Two Variables

Practice O(n) Read the full explanation

You get an integer n, the number of steps in a staircase. Each move takes you up 1 step or 2 steps.

Return how many different ways you can climb from the bottom to exactly the top.

The order of the moves matters. For example, 1 + 2 and 2 + 1 are two different ways.

Example 1:

Input: n = 4
Output: 5
Explanation: The five ways are:
1. 1 + 1 + 1 + 1
2. 1 + 1 + 2
3. 1 + 2 + 1
4. 2 + 1 + 1
5. 2 + 2

Example 2:

Input: n = 1
Output: 1
Explanation: One move of 1 step is the only way.

Example 3:

Input: n = 6
Output: 13
Explanation: Group the ways by how many 2s they use:
no 2s: 1 way (1 + 1 + 1 + 1 + 1 + 1),
one 2: 5 ways (2 + 1 + 1 + 1 + 1 in any order),
two 2s: 6 ways (2 + 2 + 1 + 1 in any order),
three 2s: 1 way (2 + 2 + 2).
In total, 1 + 5 + 6 + 1 = 13.

Constraints:

  • n is from 1 to 45.
  • The answer fits in a 32-bit signed integer.
  • For n = 45, the answer is 1,836,311,903.

STEP 1 OF 6
    Ctrl + Enter to check

    C++ · DYNAMIC PROGRAMMING

    Climbing Stairs in C++, explained

    Problem overview

    The method climbStairs receives the number of steps n and returns in how many distinct ways you can climb them, taking 1 or 2 steps at a time. Order counts: 1 step then 2 is a different way from 2 steps then 1.

    For n = 3 the answer is 3 (1+1+1, 1+2, 2+1), and for n = 4 it is 5. The constraints say 1 <= n <= 45 and that the answer fits in a 32-bit integer, so a plain int is enough.

    Approach: build up from the ground

    Listing every sequence of moves works for tiny n, but the number of sequences grows quickly. A better question is about the last move. To stand on step i, you came either from step i - 1 with a 1-step move, or from step i - 2 with a 2-step move. These two groups of ways don't overlap, so

    ways(i) = ways(i - 1) + ways(i - 2)

    That is dynamic programming: each answer is built from answers to smaller versions of the same problem. Since ways(i) only needs the two previous values, there is no need for a table. Two variables, moved forward one step at a time, are enough.

    The base cases are what make the formula start. There is one way to be on step 0, the ground: don't move. There is one way to reach step 1: a single 1-step move. Counting the ground as 1 makes step 2 come out right, since 1 + 1 = 2.

    A direct recursive version, climbStairs(n - 1) + climbStairs(n - 2), follows the same formula but solves the same smaller problems over and over: climbStairs(2) alone is recomputed many times when n is 45. Going from the bottom up computes each value exactly once, which is the whole improvement.

    Step by step

    1. Create prev as 1. It holds the ways to stand on step 0.
    2. Create curr as 1. It holds the ways to reach step 1. When n is 1 the loop below never runs, and curr is already the answer.
    3. Loop from step 2 up to n inclusive. The condition is i <= n: step n is the top and needs its count too. At the start of each round, curr is the count for step i - 1 and prev for step i - 2.
    4. Add the two counts into ways. This is the formula above, for step i.
    5. Slide the window up one step. prev takes the value of curr, then curr takes ways. The order matters: if curr were changed first, prev would copy the new value and the old one would be lost.
    6. Return curr. After the last round it holds the count for step n.

    The solution in C++

    class Solution {
    public:
        int climbStairs(int n) {
            int prev = 1;
            int curr = 1;
            for (int i = 2; i <= n; i++) {
                int ways = prev + curr;
                prev = curr;
                curr = ways;
            }
            return curr;
        }
    };
    

    Here is what the variables hold for n = 4, after each round of the loop:

    iwaysprevcurr
    2212
    3323
    4535

    The function returns 5, matching the five ways listed in the statement.

    Some C++ details:

    • ways lives inside the loop. It is declared in the loop body, so each round gets a fresh variable. Nothing outside the loop needs it.
    • The sequence is Fibonacci. The counts for n = 1, 2, 3, 4, 5, 6, 7 are 1, 2, 3, 5, 8, 13, 21. The code is the usual two-variable Fibonacci loop, shifted by one position.
    • Signed overflow is undefined behaviour. For n = 45 the function returns 1836311903, which fits in an int. The next value, for n = 46, is 2971215073, which doesn't. Signed overflow in C++ isn't guaranteed to wrap: the behaviour is undefined, so the bound n <= 45 in the statement matters.

    Complexity

    Time: O(n). The loop runs n - 1 times with a constant amount of work in each round.

    Space: O(1). Three integers, whatever the value of n. Keeping a whole vector of counts would also work, but costs O(n) memory for no benefit, since only the last two entries are ever read.

    Edge cases and common mistakes

    • n = 1. The loop condition 2 <= 1 is false, so the function returns curr, which is 1. That is why curr starts at 1 and not 0.
    • n = 2. One round runs: ways = 1 + 1 = 2. This is where counting the ground as 1 pays off.
    • Using i < n. The loop stops one step early and returns the count for step n - 1. For n = 4 it would give 3 instead of 5.
    • Assigning in the wrong order. With curr = ways; before prev = curr;, both variables end up equal to ways and the sequence doubles instead of following the formula. For n = 4 that version returns 8 instead of 5.
    • Plain recursion. climbStairs(n - 1) + climbStairs(n - 2) is correct but recomputes the same values again and again, so it takes exponential time and is too slow for n = 45.

    Testing

    • n = 1 gives 1.
    • n = 2 gives 2.
    • n = 3 gives 3.
    • n = 4 gives 5.
    • n = 10 gives 89.
    • n = 45 gives 1836311903.
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free