Climbing Stairs
You are climbing a staircase. It takes _n _steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note:Given _n _will be a positive integer.
Example 1:
Example 2:
Analysis
DP - Bottom Up Approach
Break this problem into subproblems, with optimal substructure, thus using Dynamic Programming (Bottom Up approach):
State:
dp[i]
- number of ways to reach theith
stepState Transfer Function:
dp[i] = dp[i - 1] + dp[i - 2]
- taking a step from (i - 1), or taking a step of 2 from (i - 2)Initial State:
dp[0] = 0;
dp[1] = 1;
dp[2] = 2;
Answer:
dp[n]
Complexity Analysis
Time complexity: O(n). Single loop up to
n
.Space complexity : O(n).
dp
array of sizen
is used.
DP - Top-Down Approach - Recursion with memorization
We could define memo[]
to store the number of ways to ith
step, it helps pruning recursion. And the recursive function could be defined as climb_Stairs(int i, int n, int memo[])
that returns the number of ways from ith
step to nth
step.
Complexity Analysis
Time complexity : O(n). Single loop upto n.
Space complexity : O(n). dpdp array of size n is used.
DP - Fibonacci Number - Optimize Space Complexity
Fib(n)=Fib(n−1)+Fib(n−2)
That the nth number only has to do with its previous two numbers, thus we don't have to maintain a whole array of results, just the last 2 results are enough. Thus optimized the space for O(1).
Complexity Analysis
Time complexity :
O(n)
. Single loop upto n is required to calculaten th
fibonacci number.Space complexity :
O(1)
. Constant space is used.
Solution
Dynamic Programming - Bottom Up - O(n) space, O(n) time (3ms 32.02% AC)
Dynamic Programming - Recursion with memorization - Top Down - O(n) Space, O(n) Time (3ms 32.02%)
DP - Fibonacci Numbers - Space Optimized (2ms 92.09%)
Reference
Last updated