In the 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?
Example 1:
Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
- 1 step + 1 step
- 2 steps
Example 2:
Input: n = 3
Output: 3
Explanation: There are three ways to climb to the top.
- 1 step + 1 step + 1 step
- 1 step + 2 steps
- 2 steps + 1 step
Constraints:
- 1 <= n <= 45
Solution in C Programming
// Climbing stairs: Distinct ways can you climb to the top
int climbStairs(int n){
// Base cases n = 0, 1 or 2, return n
if((n == 0) || (n == 1) || (n == 2))
return n;
int *result = (int *)calloc(n, sizeof(int));
int i = 0;
result[i++] = 1; // For the stair 1, it can be climbed in only one way
result[i++] = 2; // For the stair 2, it can be climed 1-1 or 2, so 2 ways
// Calculate for the n steps by calculating till n-1 steps and n-2 steps
for(i = 2; i < n; i++) {
result[i] = result[i-1] + result[i-2];
}
return result[n - 1];
}
Solution in C++ Programming
class Solution {
public:
int helper(int i, int n) {
if(i == n)
return 1;
if(i > n)
return 0;
return helper(i + 1, n) + helper(i + 2, n);
}
int climbStairs(int n) {
return helper(0, n);
}
};
Solution in Java Programming
class Solution {
public int climbStairs(int n) {
if(n==1)
return 1;
else if(n==2)
return 2;
else
{
int a=1,b=2,c=0,i;
for(i=3;i<=n;i++)
{
c=a+b;
a=b;
b=c;
}
return c;
}
}
}
Solution in Python Programming
class Solution:
def climbStairs(self, n):
def dynprog(m, memo={}):
if m in memo:
return memo[m]
if m <= 2:
return m
memo[m] = dynprog(m-1, memo) + dynprog(m-2, memo)
return memo[m]
res = dynprog(n, {})
return res
Solution in C# Programming
public class Solution {
Dictionary<int, int> map = new Dictionary<int, int>();
public int ClimbStairs(int n) {
if(n <= 2) return n;
if(map.ContainsKey(n))
return map[n];
int cal = ClimbStairs(n - 2) + ClimbStairs(n-1);
map.Add(n, cal);
return cal;
}
}
Also read,