题目
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0,第1项是1)。n<=39
循环
- 实现思路
前两项已知,第3项=第2项+第1项,第4项=第3项+第2项,以此类推,向后递加即可。 - 代码
public class Solution {
public int Fibonacci(int n) {
//输入负数或0直接返回0
if(n <= 0){
return 0;
}
//前两项值为1
if(n == 1 || n == 2){
return 1;
}
//定义变量
int first = 1;
int second = 1;
int result = 0;
for (int i =3; i <= n; i++) {
result = (int) ((first + second) % (1e9+7));//模(1e9 + 7) 防止数字溢出
second = first;
first = result;
}
return result;
}
}
- 运行结果
递归
- 实现思路
想得到第n项=第n-1项+第n-2项,依次类推第3项=第2项+第1项,第1项和第2项已知为1,所以递归终止条件就为n=2或n=1。 - 代码
public class Solution {
public int Fibonacci(int n) {
if(n <= 0) return 0;
if(n == 1 || n == 2) return 1;
return Fibonacci(n-1) + Fibonacci(n-2);
}
}
- 运行结果
优化递归
- 优化思路
采用动态规划思想,记录子问题值,减少重复计算。 - 代码
public class Solution {
public int Fibonacci(int n) {
if(n <= 0) return 0;
return fun1(1,1,n);
}
public static int fun1(int first,int second,int n){
if(n == 1){
return first;
}else if(n == 2){
return second;
}else if(n ==3){
return first+second;
}
return fun1(second,second+first,n-1);
}
}
- 运行结果