1.题目(一):
写一个函数,输入n,求斐波那契(Fibonacci)数列的第n项。
2 .思路
如果直接写递归函数,由于会出现很多重复计算,效率非常底,不采用。
要避免重复计算,采用从下往上计算,可以把计算过了的保存起来,下次要计算时就不必重复计算了:先由f(0)和f(1)计算f(2),再由f(1)和f(2)计算f(3)……以此类推就行了,计算第n个时,只要保存第n-1和第n-2项就可以了。
3.代码实现
public class Solution {
public static int Fibonacci(int n) {
int result=0;
if(n<0){
try {
throw new Exception("输入不合法");
} catch (Exception e) {
e.printStackTrace();
}
}else if(n==0){
return 0;
}else{
int prepre=0;
int pre=1;
for (int i=0;i<n;i++){
prepre=pre;
pre=result;
result=pre+prepre;
}
}
return result;
}
public static void main(String[] args) {
System.out.println(Fibonacci(5));
}
}
1.题目(二):
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
2.思路:
将跳法总数记为 f(n),可以知道 f(1)=1,f(2)=2。当n>2时,第一次跳1级的话,还有f(n-1)种跳法;第一次跳2级的话,还有f(n-2)种跳法,所以可以推得f(n)=f(n-1)+f(n-2),即为斐波那契数列。
3.代码实现
public class Solution {
public static int JumpFloor(int target) {
int result=0;
if(target<0){
try {
throw new Exception("台阶数不能为0");
} catch (Exception e) {
e.printStackTrace();
}
}else if(target==1){
return 1;
}else if(target==2){
return 2;
}else{
int prepre=1;
int pre=2;
for (int i=2;i<target;i++){
result=prepre+pre;
prepre=pre;
pre=result;
}
}
return result;
}
public static void main(String[] args) {
System.out.println(JumpFloor(3));
}
}