Climbing Stairs || C++ solution with O(1) space and O(n) time
Climbing Stairs
You have to climb n steps on a stair, each time you can either climb 1 step or 2 steps. You have to return the number of ways you can climb.
Example
Input: n = 2
Output: 2
Explanation: There are two ways to climb to reach the top.
1. 1 step + 1 step = 2
2. 2 steps = 2Approach 1:
we will use dynamic programming to solve. use a top-down( recursion and memorization) approach here.
Time Complexity:
O(n) for going from n to 0
Space Complexity:
O(n) for recursion stack
O(n) for dp array
Code:
int climbStairs(int n) {
int ans=0;
int i=n;
vector<int>dp(n+2,0);
ans=climb(i,v);
return ans;
}
int climb(int i,vector<int>&dp){
if(i<0)return 0;
if(i==0){
return 1;
}
if(dp[i]!=0)return dp[i];
return dp[i]=climb(i-1,dp)+climb(i-2,dp);
}
Approach 2:
Use bottom up(tabulation) approach to solve.Time Complexity:
O(n) for going from 3 to nSpace Complexity:
O(n) for dp arrayCode:
int climbStairs(int n) {
if(n<=1)return n;
vector<int>dp(n+1,0);
dp[1]=1;
dp[2]=2;
for(int i=3;i<=n;i++){
dp[i]=dp[i-1]+dp[i-2];
}
return dp[n];
}
Approach 3:
Again use bottom-up approach but with space optimisation.Time Complexity:
O(n) for going from 3 to nSpace Complexity:
O(1) as we not using any extra spaceCode:
int climbStairs(int n) {
if(n<=1)return n;
int i=1;
int j=2;
for(int k=3;k<=n;k++){
j=i+j;
i=j-i;
}
return j;
}
Comments
Post a Comment