(1) A frog can jump up to 1 steps at a time, or jump up to 2 levels. Ask the frog to jump on an n-level step with a total number of hops.
(2) A frog can jump up to 1 steps at a time, can also jump on 2 levels ... It can also jump on the N-level, at which point the frog jumps up the level of the N-step total number of hops?
Analysis: 1) when n = 1, there are only 1 hops; when n = 2 o'clock, there are two kinds of jumps; when n = 3 o'clock, there are 3 kinds of jumps; when n = 4 o'clock, there are 5 kinds of jumps; when n = 5 o'clock, there are 8 kinds of jumping method;
The law is similar to the Fibonacci sequence
The code is as follows:
[CPP]View PlainCopy
- int Fib (int n)
- {
- if (n <= 0)
- {
- cout << "error!" << Endl;
- return-1;
- }
- if (1 = = N)
- {
- return 1;
- }
- Else if (2 = = N)
- {
- return 2;
- }
- Else
- {
- return fib (n-1) + fib (n-2);
- }
- }
2) using FIB (n) to indicate that the frog jumps on the N-Step steps of the number of hops, the frog jumps on the N-Step step number 1 (n-step Jump), set fib (0) = 1;
When n = 1 o'clock, there is only one method of jumping, that is, the 1-Step Jump: Fib (1) = 1;
When n = 2 o'clock, there are two ways of jumping, one-step and second-order jumps: fib (2) = FIB (1) + fib (0) = 2;
When n = 3 o'clock, there are three ways to jump, the first step out of one, followed by FIB (3-1) in the Jump method, the first second out of the second, there is a fib (3-2) in the Jump method, after the first jump out of third order, followed by FIB (3-3) in the Jump method
FIB (3) = FIB (2) + fib (1) +fib (0) = 4;
When n = n, there is a total of n jumps, the first step out of one order, followed by FIB (n-1) in the Jump method, after the first second out of the second, there is a fib (n-2) in the Jump method ..... ..... After the first step out of the N-order, there is a Fib (n-n) jump in the back.
FIB (n) = fib (n-1) +fib (n-2) +fib (n-3) +..........+fib (n-n) =fib (0) +fib (1) +fib (2) +.......+fib (n-1)
And because 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:
Frog Jumping Step problem