大家都知道斐波那契数列,现在要求输入一个正整数 n ,请你输出斐波那契数列的第 n 项。
斐波那契数列是一个满足
的数列
数据范围:
要求:空间复杂度
,时间复杂度
,本题也有时间复杂度
的解法
一个正整数n
输出一个正整数。
4
3
根据斐波那契数列的定义可知,fib(1)=1,fib(2)=1,fib(3)=fib(3-1)+fib(3-2)=2,fib(4)=fib(4-1)+fib(4-2)=3,所以答案为3。
1
1
2
1
public int Fibonacci (int n) {
if(n == 1 || n == 2) return 1;
return Fibonacci(n-1) + Fibonacci(n-2);
} import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param n int整型
* @return int整型
*/
public int Fibonacci (int n) {
// write code here
// 算法核心思想:递归回溯
return process(n);
}
public int process(int n) {
// 递归出口
if (n == 1 || n == 2) {
return 1;
}
// 分支搜索
return process(n - 1) + process(n - 2);
}
} public int Fibonacci (int n) {
// write code here
int resuslt = 0;
int jian1 = 0;//n-1
int jian2 = 0;//n-2
for (int i = 1; i <= n; i++) {
if (i == 1) {
jian1 = 1;
resuslt = jian1;
} else if (i == 2) {
jian2 = 1;
resuslt = jian2;
} else if (i > 2) {
resuslt = jian1 + jian2;
jian2 = jian1;
jian1 = resuslt;
}
}
return resuslt;
}
} import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param n int整型
* @return int整型
*/
public int Fibonacci (int n) {
// write code here
double squareRoot = Math.sqrt(5);
double a = (1 + squareRoot) / 2;
double b = (1 - squareRoot) / 2;
double res = (1 / squareRoot) * (Math.pow(a, n) - Math.pow(b, n));
return (int)Math.floor(res);
}
} public int Fibonacci (int n) {
int[] dp=new int[n];
dp[0]=1;
dp[1]=1;
for(int i=2;i<n;i++){
dp[i]=dp[i-1]+dp[i-2];
}
return dp[n-1];
}
} public class Solution {
public int Fibonacci(int n) {
if(n<=2)
return 1;
int []dp=new int[n+1];
dp[1]=dp[2]=1;
for(int i=3;i<=n;i++)
dp[i]=dp[i-1]+dp[i-2];
return dp[n];
}
/*public int Fibonacci(int n) {
if(n<=2)
return 1;
else
return Fibonacci(n-1)+Fibonacci(n-2);
}*/
} public class Solution {
public int Fibonacci(int n) {
// 1.递归
// 2.记录table
int[] table = new int[n];
return fib(n, table);
}
private int fib(int n, int[]table) {
// 递归结束条件
if (n == 1 || n == 2) {
return 1;
}
// 数组中存在,直接返回,避免重复计算
if (table[n - 1] != 0) {
return table[n - 1];
}
int res = fib(n - 1, table) + fib(n - 2, table);
// 结果保存进数组,以免重复计算
table[n - 1] = res;
return res;
}
}
class Solution { public: int Fibonacci(int n) { int f = 0, g = 1; while(n--) { g += f; f = g - f; } return f; } };