Count ways to N'th Stair(Order does not matter)
JavaView on GFG
Time: O(n)
Space: O(n)
Advertisement
Intuition
Count ways to reach nth stair using steps 1 or 2 (order does NOT matter). Same as coin change count with coins {1,2}.
Algorithm
- 1dp[i] = number of unordered ways to reach stair i. dp[i] = dp[i-1] + (i%2==0 ? 1 : 0) ... actually: floor(n/2) + 1.
Common Pitfalls
- •Unordered: only care about how many 2-steps used. If k two-steps: uses 2k + (n-2k) one-steps. k = 0..n/2, so answer = floor(n/2) + 1.
Count ways to N'th Stair(Order does not matter).java
Java
// Approach: DP equivalent to partition into 1s and 2s. dp[i] = dp[i-1] (use 1) + dp[i-2]/some partition formula.
// Time: O(n) Space: O(n)
class Solution {
public long nthStair(int n) {
int[] dp = new int[n + 1];
dp[0] = 1;
dp[1] = 1;
for (int i = 2; i <= n; i++)
dp[i] = 1 + Math.min(dp[i - 1], dp[i - 2]);
return dp[n];
}
}Advertisement
Was this solution helpful?