You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
classAlgorithmic {
intclimbStairs(int n) {
if (n ==0|| n ==1|| n ==2|| n ==3) {
return n;
}
int sum =0;
int left =1;
int right =2;
for (int i =2; i < n; i++) {
sum = left + right;
left = right;
right = sum;
}
return sum;
}
}
Recursive
classRecursive {
intclimbStairs(int n) {
//handle invalid casesif (n <0) return0;
//base case 1: if reached 0 or 1-> 1if (n ==0|| n ==1) return1;
//the current position will be the sum of the last two onesreturnclimbStairs(n -1) +climbStairs(n -2);
}
}
Mathematical
classMathematical {
// Runtime: 306 ms, faster than 97.73% of Dart online submissions for Climbing Stairs.// Memory Usage: 155.3 MB, less than 13.64% of Dart online submissions for Climbing Stairs.intclimbStairs(int n) {
return ((1/sqrt(5.0)) *
(pow((1+sqrt(5)) /2, n +1) -pow((1-sqrt(5)) /2, n +1)))
.toInt();
}
}
Memory Efficient Tabulation
classMemoryEfficientTabulation {
// Memory Efficient Tabulation// Runtime: 452 ms, faster than 43.18% of Dart online submissions for Climbing Stairs.// Memory Usage: 140.2 MB, less than 79.55% of Dart online submissions for Climbing Stairs.intclimbStairs(int n) {
int stair1 =1;
int stair2 =1;
for (int i =2; i <= n; i++) {
int stair = stair1 + stair2;
stair1 = stair2;
stair2 = stair;
}
return stair2;
}
}
Tabulation
classTabulation {
// Runtime: 484 ms, faster than 31.82% of Dart online submissions for Climbing Stairs.// Memory Usage: 140.3 MB, less than 70.45% of Dart online submissions for Climbing Stairs.intclimbStairs(int n) {
//initialize two variables base casesint one =1, two =1;
//loop until reaching the given numberfor (int i =2; i <= n; i++) {
//save the one value in temp variableint temp = one;
//update the one value by adding the last one and current two values
one += two;
//update the two value by the old one variable value
two = temp;
}
//return the last reached valuereturn one;
}
}
Memoization
classMemoization {
intstairs(int n, List<int> stair) {
if (n <=1) {
stair[n] =1;
return1;
}
if (stair[n] !=-1) {
return stair[n];
}
int one =stairs(n -1, stair);
int two =stairs(n -2, stair);
stair[n] = one + two;
return one + two;
}
intclimbStairs(int n) {
List<int> stair = [n +1, -1];
stairs(n, stair);
return stair[n];
}
}