Skip to content
Programming101
Programming101

Learn everything about programming

  • Home
  • CS Subjects
    • IoT – Internet of Things
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programming101
Programming101

Learn everything about programming

Leetcode Climbing Stairs problem solution

YASH PAL, 31 July 2024

In this Leetcode Climbing Stairs problem solution, 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?

Leetcode Climbing Stairs problem solution

Problem solution in Python.

def climbStairs(self, n: int) -> int:
        def dp(n, cache):
            if n not in cache:
                cache[n] = dp(n-1, cache) + dp(n-2, cache)
            return cache[n]
        return dp(n, {1: 1, 2: 2})

Problem solution in Java.

class Solution {
    
    int [] cache = new int[46];
    
    public int climbStairs(int n) {
        
        if(n < 0) return 0;
        
        if(n == 0) return 1;
        
        int val = cache[n];
        
        if(val != 0)
            return val;
        
        val = climbStairs(n - 1) + climbStairs(n - 2);
        
        cache[n] = val;
        
        return val;
    }
}

Problem solution in C++.

class Solution {
public:
    int climbStairs(int n) {
        vector<int>dp;
        dp.resize(n+1);
        dp[0] = 1;
        dp[1] = 1;
        for(int i = 2; i<=n; i++){
            dp[i] = dp[i-1] + dp[i-2];
        }
        return dp[n];
    }
};

Problem solution in C.

int climbStairs(int n){
    int* a = (int*)malloc(sizeof(int)*2);
    
    a[0] = 1;
    a[1] = 1;
    
    for (int i=2;i<=n;i++){
        a[i%2] =  a[0] + a[1];
    }
    return a[n%2];
}

coding problems

Post navigation

Previous post
Next post
  • HackerRank Separate the Numbers solution
  • How AI Is Revolutionizing Personalized Learning in Schools
  • GTA 5 is the Game of the Year for 2024 and 2025
  • Hackerrank Day 5 loops 30 days of code solution
  • Hackerrank Day 6 Lets Review 30 days of code solution
©2025 Programming101 | WordPress Theme by SuperbThemes