clueless coding // TODO: be smarter

LeetCode 70. Climbing Stairs: Java Solution



Problem Statement


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

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Function Signature (Java):
  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


public int climbStairs(int n) {

   if (n <= 2) {
       return n;
   }

   int oneBefore = 2;
   int twoBefore = 1;
   int curr = 0;

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

   return curr;

}