clueless coding // TODO: be smarter

LeetCode 70. Climbing Stairs: C++ Solution



Problem Statement


You are climbing a staircase. It takes n steps to reach to the top.

You can only climb 1 or 2 steps at a time.

Design an algorithm to find how many distinct ways can you climb to the top.

Function Signature (C++):
  int climbStairs(int n)

Inputs:
  n = 2

Outputs:
  2

You can get to step 2 two different ways.
1 step + 1 step
2 step

Inputs:
  n = 3

Outputs:
  3

You can get to step 2 two different ways.
1 step + 1 step + 1 step
2 step + 1 step
1 step + 2 step



TL;DR Code Solution


int climbStairs(int n) {

    if (n < 3) {
        return n;
    }

    int twoBefore = 1;
    int oneBefore = 2;
    int result;

    for (int i = 3; i <= n; i++) {
        result = oneBefore + twoBefore;
        twoBefore = oneBefore;
        oneBefore = result;
    }

    return result;

}