Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
911 views
in Technique[技术] by (71.8m points)

algorithm - 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,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...