Climbing Staircase

You are climbing a staircase that requires steps to reach the top. Each time, you can climb either 1 or 2 steps. Determine the number of distinct ways to reach the top.

Examples

Example 1:

  • Input:
  • Output: 2
  • Ways: (1+1), (2)

Example 2:

  • Input:
  • Output: 3
  • Ways: (1+1+1), (1+2), (2+1)

Strategy

This problem follows the Fibonacci sequence pattern. To reach step , you must have come from either step (taking 1 step) or step (taking 2 steps):

A naive recursive solution has exponential time complexity . The solution employs memoization using a hash map to store computed values, similar to the optimization techniques used in House Robber. This reduces time complexity to with space.

Solution

#include <unordered_map>
using namespace std;
 
class Solution {
public:
  unordered_map<int, int> createHash() {
    unordered_map<int, int> hashMap;
    hashMap[1] = 1;
    hashMap[2] = 2;
    return hashMap;
  }
  unordered_map<int, int> hashMap = createHash();
  int climbStairs(int n) {
    if (hashMap.count(n))
      return hashMap[n];
    hashMap[n] = climbStairs(n - 1) + climbStairs(n - 2);
    return hashMap[n];
  }
};