Fibonacci的公式:f(n+2) = f(n+1) + f(n)。
在面试中,也会有Fibonacci的变形出现,例如:
已知有n级台阶,每次只能上2级或者1级,问一共有多少种上法?
如果检查整个数列会发现,这个数列的同项公式正是Fibonacci,只不过数列的前两项是1和2.
在面试中,也会有Fibonacci的变形出现,例如:
已知有n级台阶,每次只能上2级或者1级,问一共有多少种上法?
如果检查整个数列会发现,这个数列的同项公式正是Fibonacci,只不过数列的前两项是1和2.
public class Stairs {
public static void main(String[] args) {
// TODO Auto-generated method stub
int Fibonnqi = 10;
System.out.println(Fib(Fibonnqi));
System.out.println(UnrecursiveFib(Fibonnqi));
}
public static int Fib(int num){
if(num == 1)
return 1;
else if(num == 2)
return 1;
else{
return Fib(num-1) + Fib(num-2);
}
}
public static int UnrecursiveFib(int num){
if(num==1 || num==2)
return 1;
else{
int a = 1;
int b = 1;
int next = 0;
for(int i=2; i<num; i++){
next = a + b;
a = b;
b = next;
}
return next;
}
}
}
2208

被折叠的 条评论
为什么被折叠?



