Using C + + recursion to solve jump-step problem _c language

Source: Internet
Author: User

Topic:

A step has a total of n-level, if you can jump 1, you can jump 2 level. How many jumps are there in total?

Analysis:

It is also a relatively basic topic, which can be easily solved by recursion.
The FIB (n) is used to denote the number of jumps of N-step steps, the frog jumps up to the N-Step step number 1 (n-step Jump) and sets the FIB (0) = 1;
When n = 1 o'clock, there is only one method of jumping, that is, 1-step Jump: Fib (1) = 1;
When n = 2 o'clock, there are two ways of jumping, first and second order jumps: Fib (2) = Fib (1) + Fib (0) = 2;
When n = 3 o'clock, there are three kinds of ways to jump, the first step out of one, followed by FIB (3-1) in the Jump method; The first time out of second order, followed by FIB (3-2) in the Jump method; The first time out of the third Order, followed by the FIB (3-3) in the Jump method
Fib (3) = Fib (2) + FIB (1) +fib (0) = 4;
When n = n, there are n ways to jump, the first step out of a there is also fib (n-1) in the back of the Jump method, the first time out of the second order, there are fib (n-2) in the Jump method ... ..... The first time to jump out of the N-order, there are Fib (n-n) in the back of the jump method.
Fib (n) = Fib (n-1) +fib (n-2) +fib (n-3) +..........+fib (n-n) =fib (0) +fib (1) +fib (2) +.......+fib (n-1)
Also because of Fib (n-1) =fib (0) +fib (1) +fib (2) +.......+fib (n-2)
Two-type subtraction: Fib (n)-fib (n-1) =fib (n-1) ===== "Fib (n) = 2*fib (n-1) n >= 2
The recursive equation is as follows:

The code is implemented as follows (GCC compiles through):

#include "stdio.h"
#include "stdlib.h"
 
int function (int n);
 
int main (void)
{
  int tmp;
   
  TMP = function (5);
  printf ("%3d\n", TMP);
 
  return 0;
}
 
int function (int n)
{
  if (n = 1) return
    1;
  else if (n = = 2) return
    2;
  else return  
    function (n-1) + function (n-2);
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.