Climbing Stairs Easy 0 attempts
LeetCode ↗

Climbing Stairs

Easy Dynamic ProgrammingMemoization LeetCode

You're at the bottom of a staircase with n steps, and each move lets you go up either 1 or 2 steps at a time. Work out how many distinct sequences of moves will get you to the top.

Input Format
Implement climbStairs(n). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Return the result described in the statement.

Sample Input and Output

Example 1 ยท Run Sample

Input
n = 2
Output
2

Example 2

Input
n = 3
Output
3

Example 3

Input
n = 5
Output
8
Constraints
  • 1 <= n <= 45
Test Cases (3)
Case 1
Args: [2] Expected: 2
Case 2
Args: [3] Expected: 3
Case 3
Args: [5] Expected: 8

Dynamic Programming (Fibonacci)

javascript
function climbStairs(n) {
  if (n <= 2) return n;
  let a = 1, b = 2;
  for (let i = 3; i <= n; i++) [a, b] = [b, a + b];
  return b;
}

Time: O(n) | Space: O(1)

Saved in this browser only. Private to you.

JavaScript