Im solving a recursion problem in which the function int stairs(int n) returns the number of possibilities in climbing the stairs up to n, with the conditions of either taking 1 step or 2 steps. The following code solves this:
int stairs(int n)
{
if (n<0) return 0;
if (n==0) return 1;
return stairs(n-1) + stairs(n-2);
}
Now i have a constraint that says: if you reach the 20th floor, you MUST use an elevator which takes you automatically all the way up to the n'th floor. If for some reason you skip level 20 (for instance, get to level 19 and then climb 2 floors to level 21), continue as usual. Find the number of possibilities for the constraint above. What I've done so far is this:
int stairs20(int n)
{
if (n<=20) return stairs(n);
return stairs(20) + stairs(n-21);
}
The logic behind the code is to calculate the number of possibilities in reaching the 20th floor, and the number of possibilities from the 21st floor and up. I presume this does not retrieve the correct answer and would appreciate advice on where is my mistake or what am I not calculating?
The work you did in climbing the stairs is the force you applied (your weight) times the distance you moved upward (the height of the stairs.) That is: Work (in joules) = your weight (in newtons) X the height of the stairs (in meters.)
Each time we increment n, the number of ways to climb the staircase is the sum of the previous two ways. That means that we can solve the staircase problem by solving for the Fibonacci number at each stair, until we get to n.
4. Who Should Avoid Climbing Stairs As a Form of Exercise? Those who are suffering from hip or knee problems and those who have acute heart conditions should refrain from climbing stairs as a form of exercise.
There are 274 ways to climb the stairs.
When n>20
,
you can first reach 20th floor, then go all the way up => stairs(20)
you can also reach 19th floor, then go to 21st floor, from 21st floor, you have stairs(n-21)
ways to floor n, so => stairs(19)*stairs(n-21)
So sum it up is stairs(20) + stairs(19) * stairs(n-21)
.
You may use dynamic programming to avoid calculating the same value.
The basic recursion scheme is the following
int stairs(unsigned int n) {
if (n < 2)
return 1;
return stairs(n-1) + stairs(n-2);
}
Now, the question you must ask yourself is how the rule applied to stair 20 will modify the recursion scheme ? If n > 20
, then stairs(n)
will be equal to stairs(20) + <number_of_ways_to_climb_to_n_without_reaching_floor20)
. How do you avoid floor 20 ? By reaching floor 19 and going straight to floor 21. Then, at floor 21, you must climb until you get to floor n.
There are thus stairs(19)*stairs(n-21)
to reach floor n
without stopping at floor 20.
The final answer is therefore :
int stairs20(unsigned int n) {
if(n > 20) {
return stairs(20) + stairs(19)*stairs(n-21);
} else {
return stairs(n);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With