Climbing Stairs (LeetCode)
Problem Descriptionβ
Problem Statement | Solution Link | LeetCode Profile |
---|---|---|
Merge Two Sorted Lists | Merge Two Sorted Lists Solution on LeetCode | VijayShankerSharma |
Problem Descriptionβ
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?
Examplesβ
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
Approachβ
To find the number of distinct ways to climb to the top of the staircase, we can use dynamic programming.
- Initialize an array
dp
of sizen+1
to store the number of distinct ways to reach each step. - Set
dp[0] = 1
anddp[1] = 1
since there's only one way to reach the first step and the second step. - Iterate from
2
ton
, updatingdp[i]
as the sum ofdp[i-1]
anddp[i-2]
. - Finally, return
dp[n]
, which represents the number of distinct ways to reach then
-th step.
Solution Codeβ
Pythonβ
class Solution(object):
def climbStairs(self, n):
if n <= 2:
return n
dp = [0] * (n + 1)
dp[1] = 1
dp[2] = 2
for i in range(3, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
C++β
class Solution {
public:
int climbStairs(int n) {
if (n <= 2) {
return n;
}
vector<int> dp(n + 1);
dp[1] = 1;
dp[2] = 2;
for (int i = 3; i <= n; ++i) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
};
Javaβ
class Solution {
public int climbStairs(int n) {
if (n <= 2) {
return n;
}
int[] dp = new int[n + 1];
dp[1] = 1;
dp[2] = 2;
for (int i = 3; i <= n; ++i) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
}
Conclusionβ
The "Climbing Stairs" problem can be efficiently solved using dynamic programming, where the number of distinct ways to reach each step is calculated iteratively. The provided solution code implements this approach in Python, C++, and Java, providing an optimal solution to the problem.