C language _ function recursion _ frog jump step (three cases)

The first

There are 5 steps in total, and you can jump one or two steps at a time.
Idea: Assuming that the function to complete the jump is jump(5) to
complete this action, there may be

  1. The last jump is over;
  2. Finally,
    it’s done after two jumps; 1——It’s position is on the fourth step, jump here (4);
    2——It’s position is on the third step, jump here (3) ;
    So in this case jump(5)=jump(4)+jump(3).

We then regard the total number of steps as n. The
final possible situation is

  1. The last jump is over;
  2. Finally, the jump is over after two jumps; the
    same as the previous case;
    jump(n)=jump(n-1)+jump(n-2)
    (note that there is a method when n=1, and there is when n=2 Two methods are used as exits to end recursion)
    //The reasons for 1 or 2 are discussed here
    eg: when n=3=jump(2)+jump(1); if n=2 is not considered, there are two cases
    jump(2)= jump(1)+jump(0)=1 but in fact, there are two situations when n=2 and errors will occur.
    The corresponding code is implemented as
    Insert picture description here
    Observing the output result and
    Insert picture description here
    finding that it is a Fibonacci number.

The second

There are a total of n steps, and each time you can jump 1, 2, 3 to n steps.
According to the above analysis, the
final possible situation is:
one is left, two are left...n are left;
//The method for the remaining n to this position is 0; jump(0)=0
jump(n)=jump(n-1 )+jump(n-2)…+jump(0);——1
——————— a total of n———————
corresponding to jump(n-1):
jump(n-1)= jump(n-2)+…jump(0); ——2
Formula 1 and Formula 2 are solved simultaneously
jump(n)=jump(n-1)+jump(n-1)=2*jump(n-1 );
Corresponding code:

Insert picture description here
Output result
Insert picture description here

The third

There are n steps, and you can jump 1, 2, 3...m steps each time.
Because the size of m and n is unknown, we need to discuss the possibility of jumping to the end
when m>=n
: there are
n remaining, n-1 remaining ,...1 left;
so this case is the same as the second one,
jump(n)=2*jump(n-1)

When m<n
jump to the last possible situation, there are
m jumps left-at this position it is possible to jump(nm) and
m-1 jumps are left-the position may be jump(n-(m-1))
...
left One jump is over-possible situation jump(n-1)

此时
jump(n)=jump(n-1)+jump(n-2)…+jump(n-m);
jump(n-1)=jump(n-2)…jump(n-m)+jump(n-m-1);
联立求解
jump(n)=jump(n-1)+jump(n-1)-jump(n-m-1);
jump(n)=2*jump(n-1)-jump(n-m-1);

Corresponding code
Insert picture description here
Insert picture description here
Output result
Insert picture description here

Guess you like

Origin blog.csdn.net/dodamce/article/details/113073197