Egbert Lin's Blog

“Life is not a race, but a journey to be savoured each step of the way” by Brian Dyson

[LeetCode Road] Climbing Stairs - Solution/C++

70. Climbing Stairs

Question:

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?

Example:

Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Input: n = 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

Constraints:
  • 1 <= n <= 45
  • Source code

    Version 1

    Idea:
    We must find the reqular pattern. As example mentioned, n = 2 -> output: 2, n = 3 -> output: 3.

    You can derive n = 4, n = 5, ...ect. My answer is as below and you can get the reqular result:
    n = 4 -> Output: 5 // 2 + 3
    n = 5 -> Output: 8 // 3 + 5
    n = 6 -> Output: 13 // 5 + 8
    n = 7 -> Output: 21 // 8 + 13
    (Results: 1 2 3 5 8 13 21 ...)

    Isn't it like classical problem of Fibonacci Sequence? So, I directly think recursion can solve it. The approach is as below, but the recursion can't pass the submission, because it will show Time Limit Exceeded when n = 44.

    1
    2
    3
    4
    5
    6
    7
    class Solution {
    public:
    int climbStairs(int n) {
    if(n == 1) return 1;
    if(n == 2) return 2;
    return climbStairs(n - 1) + climbStairs(n - 2);
    };

    Version 2

    Idea:
    The strategy of second approach is an iterator. We can use for loop instead of recursion. Very simple coding as below and it can pass the submission.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    class Solution {
    public:
    int climbStairs(int n) {
    if(n == 1) return 1;
    if(n == 2) return 2;

    int result = 0;
    int prev = 1;
    int next = 2;
    for(int i = 2; i < n; i++){
    result = prev + next;
    prev = next;
    next = result;
    }
    return result;
    }
    };