Climbing Stairs LeetCode Solution

Here, We see Climbing Stairs LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc., with different approaches.

List of all LeetCode Solution

Climbing Stairs LeetCode Solution

Climbing Stairs LeetCode Solution

Problem Statement

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 1:
Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2:
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

Climbing Stairs Leetcode Solution C++

class Solution {
public:
    int dp[46];
    int climbStairs(int n) {
        if(dp[n]!=0) return dp[n];
  
        if(n==1 || n==2) return n;
        dp[n]=climbStairs(n-1)+climbStairs(n-2);
        return dp[n];
    }
};
Code language: C++ (cpp)

Climbing Stairs Leetcode Solution Java

class Solution {
    public int climbStairs(int n) {
        if(n == 0 || n == 1 || n == 2){return n;}
    int[] mem = new int[n];
    mem[0] = 1;
    mem[1] = 2;
    for(int i = 2; i < n; i++){
        mem[i] = mem[i-1] + mem[i-2];
    }
    return mem[n-1];
    }
}
Code language: Java (java)

Climbing Stairs Leetcode Solution JavaScript

var climbStairs = function(n) {
    let prev = 0;
    let curr = 1;
    let tmp;
    for(let i = 1; i <= n; i++){
         tmp = prev;
        prev = curr;
      curr += tmp;
   }
   return curr;
};
Code language: JavaScript (javascript)

Climbing Stairs Leetcode Solution Python

class Solution(object):
    def climbStairs(self, n):
        a, b = 1, 1
        for i in range(n):
            a, b = b, a + b
        return a
Code language: Python (python)
Scroll to Top