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:
Input:
2
Output:
2
Explanation:
There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 stepsExample 2:
Input:
3
Output:
3
Explanation:
There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 stepAnalysis
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 theithstepState 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).
dparray of sizenis 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 thfibonacci 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
Was this helpful?