70. Climbing Stairs
Explanation
To solve this problem, we can use dynamic programming. We can define a DP array where dp[i]
represents the number of distinct ways to reach step i
. We can then build up this array iteratively by considering the number of ways to reach the current step based on the number of ways to reach the previous two steps.
- Initialize a DP array of size
n+1
to store the number of ways to reach each step. - Set
dp[0] = 1
anddp[1] = 1
as there is only 1 way to reach the first and second steps. - Iterate from
i = 2
up ton
and calculatedp[i]
based on the sum ofdp[i-1]
anddp[i-2]
, as you can climb either 1 or 2 steps at a time. - Return
dp[n]
as the final answer.
Time Complexity: O(n)
Space Complexity: O(n)
class Solution {
public int climbStairs(int n) {
if (n <= 1) {
return 1;
}
int[] dp = new int[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];
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.