704431. Count ways to N'th Stair(Order does not matter)
Count ways to N'th Stair(Order does not matter)
Slug: count-ways-to-nth-stairorder-does-not-matter5639 Difficulty: Medium Id: 704431 Topic Tags: Dynamic Programming, Mathematical, Algorithms Company Tags: Accolite, Amazon
Summary
We are asked to find the number of ways to climb N stairs, where each step can be either one or two units. The order of climbing does not matter. This problem is a classic example of dynamic programming and mathematical optimization.
Detailed Explanation
The key insight here is that the number of ways to climb N stairs depends on the last step taken. If we take one step, then the remaining steps are equivalent to climbing N-1 stairs. If we take two steps, then the remaining steps are equivalent to climbing N-2 stairs. This recursive relationship allows us to build a dynamic programming solution.
Here's a step-by-step breakdown of the solution:
- Create an array
dpof size N+1, wheredp[i]represents the number of ways to climb i stairs. - Initialize
dp[0] = 1, since there is one way to climb 0 stairs (i.e., not climbing at all). - For each step from 1 to N, calculate
dp[i]as follows:- If we take one step to reach the ith stair, then the remaining steps are equivalent to climbing i-1 stairs. Therefore, add
dp[i-1]to the current value. - If we take two steps to reach the ith stair, then the remaining steps are equivalent to climbing i-2 stairs. Therefore, add
dp[i-2]to the current value.
- If we take one step to reach the ith stair, then the remaining steps are equivalent to climbing i-1 stairs. Therefore, add
- The final answer is
dp[N], which represents the number of ways to climb N stairs.
Here's a diagram illustrating this process:
0: 1
1: 1 + dp[0]
2: dp[1] + dp[0]
...
N: dp[N-1] + dp[N-2]
Time complexity: O(N) Space complexity: O(N)
Optimized Solutions
Java
public class CountWaysToNthStair {
public static int countWays(int n) {
int[] dp = new int[n+1];
dp[0] = 1;
for (int i = 1; i <= n; i++) {
dp[i] = dp[i-1] + dp[i-2];
}
return dp[n];
}
}