Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain this dynamic programming climbing n-stair code

Problem is

"You are climbing a stair case. Each time you can either make 1 step or 2 steps. The staircase has n steps. In how many distinct ways can you climb the staircase?"

Following is the code solution for this problem but I am having trouble understanding it. Can anybody explain me

int stairs(int n) {
  if (n == 0) return 0;
  int a = 1;
  int b = 1;
  for (int i = 1; i < n; i++) {
    int c = a;
    a = b;
    b += c;
  }
  return b;
 }

Thanks,

like image 812
Deepesh M Avatar asked Mar 30 '13 17:03

Deepesh M


People also ask

How do you solve climbing stairs?

Solution Idea If we take one step from the ground, then the smaller sub-problem = climbing the nth stair from the 1st stair. If we take the two-step from the ground, then the smaller sub-problem = climbing the nth stair from the 2nd stair.

What are the benefits of climbing stairs?

Climbing stairs can improve the amount of "good cholesterol" in the blood. Stair climbing increases leg power and may be an important priority in reducing the risk of injury from falls in the elderly. Stair climbing can help you achieve and maintain a healthy body weight.

How many ways to climb stairs if you can go 1 or 2 steps at a time?

There are 274 ways to climb the stairs.

What is climbing stairs in physical education?

Stair climbing is a vertical exercise where you push down to lift your entire body up a stair. This type of exercise can increase the strength of the leg, thigh and hip muscles while also toning the abdominal muscles. Climbing stairs can also help build muscle mass in the lower body.


1 Answers

Well, first you need to understand the recursive formula, and how we derived the iterative one from it.

The recursive formula is:

f(n) = f(n-1) + f(n-2)
f(0) = f(1) = 1

(f(n-1) for one step, f(n-2) for two steps, and the total numbers is the number of ways to use one of these options - thus the summation).

If you look carefully - this is also a well known series - the fibonacci numbers, and the solution is simply calculating each number buttom-up instead of re-calculating the recursion over and over again, resulting in much more efficient solution.

like image 188
amit Avatar answered Oct 13 '22 20:10

amit