Last updated on January 20th, 2025 at 10:53 pm
Here, we see a Climbing Stairs LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.
List of all LeetCode Solution
Topics
Companies
Adobe, Apple
Level of Question
Easy
Climbing Stairs LeetCode Solution
Table of Contents
1. 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
2. Coding Pattern Used in Solution
The provided code solves the “Climbing Stairs” problem, which is a classic Fibonacci Numbers problem. The goal is to determine the number of distinct ways to climb a staircase with n
steps, where you can take either 1 or 2 steps at a time.
This problem is solved using Dynamic Programming (DP) in all implementations, but the specific approaches differ slightly.
3. Code Implementation in Different Languages
3.1 Climbing Stairs 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]; } };
3.2 Climbing Stairs 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]; } }
3.3 Climbing Stairs 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; };
3.4 Climbing Stairs Python
class Solution(object): def climbStairs(self, n): a, b = 1, 1 for i in range(n): a, b = b, a + b return a
4. Time and Space Complexity
Time Complexity | Space Complexity | |
C++ | O(n) | O(n) |
Java | O(n) | O(n) |
JavaScript | O(n) | O(n) |
Python | O(n) | O(n) |
- C++ uses recursion with memoization, which requires both a
dp
array and stack space for recursion. - Java uses an iterative approach with an array, which avoids recursion but still requires O(n) space for the array.
- JavaScript and Python use an optimized iterative approach with constant space, making them more efficient in terms of memory usage.