-
-
- Find the nth term of the Fibonacci sequence
- A frog can jump up 1 steps at a time, or 2 steps at a time. Find how many ways the frog can jump up a n-level stair.
- A frog can jump up 1 steps at a time, it can jump up 2 steps...it can also jump up n steps. Find the total number of ways the frog can jump up a n steps
-
Find the nth term of the Fibonacci sequence
- recursion
public int Fibonacci(int n){
int[] result = {0,1};
if(n<2)
return result[n];
return Fibonacci(n-1)+Fibonacci(n-2);
}
- non-recursive
public int Fibonacci(int n){
int[] result = {0,1};
if(n<2)
return result[n];
int sum = 0;
int left = 0;
int right = 1;
for(int i=2;i<=n;i++){
sum = left + right;
left = right;
right = sum;
}
return sum;
}
A frog can jump up 1 steps at a time, or 2 steps at a time. Find how many ways the frog can jump up a n-level stair.
Ideas:
If you jump 1 step for the first time, the remaining n-1; if you jump 2 steps, the remaining n-2;
A frog can jump up 1 steps at a time, it can jump up 2 steps...it can also jump up n steps. Find the total number of ways the frog can jump up a n steps
With the above foreshadowing, if you jump 1 step for the first time, there will be n-1 remaining; if you jump 2 steps for the first time, there will be n-2 remaining;
if you jump 3 steps for the first time, there will be n-3 remaining. . . .
Subtract two formulas
public class Solution {
public int JumpFloorII(int target) {
int[] result = {0,1};
if(target<2)
return result[target];
int sum = 1;
for(int i=2;i<=target;i++){
sum *= 2;
}
return sum;
}
}