Technology Sharing

[Likou] Daily Question - Question 70, Climbing Stairs

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

topic:

Suppose you are climbing a staircase. It takes n steps for you to reach the top.

You can climb 1 or 2 steps at a time. How many different ways can you get to the top of the building?

Ideas:

I started by writing a function to calculate the number of people climbing the first and second floors, and then sorted and summed them, but it exceeded the range. Later I changed the range, but the result was wrong...

I don't know why.

Later I looked at the result and it looked more and more familiar. Isn't this the Fibonacci sequence?

It will be later

Result code:

  1. int climbStairs(int n) {
  2.   //int n,j;
  3.   int sum=0;
  4.   //scanf("%d",&n);
  5.   int f_1=1;
  6.   int f_2=2;
  7.   int f_n=0;
  8.   //int f_n_1=0;
  9.   if(n==0||n==1||n==2)
  10.   {
  11.       return n;
  12.   }
  13.   for(int i=1;i<=n-2;i++)
  14.   {
  15.       f_n=f_1+f_2;
  16.       //f_n_1=f_n+f_2;
  17.       f_1=f_2;
  18.       f_2=f_n;
  19.   }
  20.   return f_n;
  21.   // return 0;
  22.    
  23. }

Keep up the good work!!!!!!!!!!!!!

Empty head.

If there is a better solution, please let me know, thank you!

Add a recursive method:

Recursive thinking:

The same as the Fibonacci sequence, that is, write Fibonacci recursively and finally output

See code:

  1. int *func(int n,int* f_n,int f_1,int f_2)
  2. {    
  3.   --n;
  4.   if(n == -1)
  5.       return n;  
  6.   f_n[n] = f_1+f_2;
  7.   f_1 = f_2;
  8.   f_2 = f_n[n];
  9.   func(n,f_n,f_1,f_2);
  10.   return f_n;
  11. }
  12. int climbStairs(int n) {
  13.    
  14.   int f_n[n];
  15.   func(n,f_n,0,1);
  16.   return f_n[0];
  17. }

I hope I am better today than I was yesterday!

Keep going!!