algorithm accumulation-jump step problem
topic One: A frog can jump up to 1 steps at a time, can also jump up to level 2. How many jumps are there in total for the frog to jump up the N-level steps?
parsing:
is to find the law of the algorithm, set F (n) to jump the N-Step jump method, starting from 1 to find the law:
F (1) = 1;
F (2) = 2;
F (3) = 3;
F (4) = 5;
...
F (n) = f (n-1) = f (n-2);
can be seen is the Fibonacci sequence, for this problem from the beginning of each number of n=3 is equal to the sum of the results of the first two. can be done recursively or iteratively, because recursion contains a lot of repetition, so it's better to use iterative efficiency.
Recursive method
public int Jump (int n) {
if (n <= 0) {
return-1;
}
Switch (n) {case
1: Return
1;
Case 2: Return
2;
Default: Return
Jump (n-1) + Jump (n-2);
}
Iterative Methods
public int Jump1 (int n) {
if (n <= 2) {return
n;
}
int fron = 1;
int NEX = 2;
int sum = 0;
for (int i = 3; I <= n; i++) {
sum = fron + NEX;
Fron = NEX;
NEX = sum;
}
return sum;
}
topic Two: A frog can jump up to 1 steps at a time, can also jump up to level 2 ... It can also jump up n levels. How many jumps are there in total for the frog to jump up an n-level step?
This problem is called crazy jump step, on the basis of common jump steps need to deepen some understanding
There are several ways to understand this problem:
First Type:
F (1) = 1;
F (2) = f (2-1) + f (2-2) = 1 + 1 = 2; The first jump step after the rest of the steps of the number of jumps + the first jump 2 order the remaining steps to jump the method
F (3) = f (3-1) + f (3-2) + f (3-3) = f (2) + f (1) +1 = 4 ;//meaning similar to
f (4) = f (4-1) + f (4-2) + f (4-3) + f (4-4) = f (3 + F (2) + f (1) + 1 = 8;
...
F (n) = f (n-1) +f (n-2) +f (n-3) +...+f (n-n);
then we can find the law: F (n) = 2*f (n-1);
The code is (you can also use an iterative method, of course):
if (n = = 1) {return
1;
}
Return JUMP1 (n-1) * 2
The second understanding: Each step has two states, except the last step must jump, jump and do not jump two states, then the method is f (n) = 2^ (n-1);
The code is:
public int Jump2 (int n) {return
(int) Math.pow (2, n-1);
}
Read the comments to learn another way, on a line of code, as follows:
personally think is the second method of another way of writing, a little read ...
public int Jump3 (int n) {return
1 <<--n;
}