链接
牛客:斐波那契数列
LeetCode:剑指 Offer 10- I. 斐波那契数列
思路
非常经典的一道题目,利用动态规划的思路。可以采取策略节省空间
F(n) = F(n-1) + F(n-2)
代码
牛客:
public class Solution {
public int Fibonacci(int n) {
if(n <= 0)
return 0;
if(n == 1)
return 1;
int first = 0;
int second = 1;
int res = 0;
for(int i = 2; i <= n; i++)
{
res = first + second;
first = second;
second = res;
}
return res;
}
}
LeetCode:
class Solution {
public int fib(int n) {
if (n == 0 || n == 1) {
return n;
}
int first = 0, second = 1;
int result = 0;
for (int i = 2; i <= n; i++) {
result = (first + second) % 1000000007;
first = second;
second = result;
}
return result;
}
}
牛客和LeetCode的区别主要在于n的取值范围,LeetCode取值范围更大,需要做取模操作。
相似题
链接:509. 斐波那契数
这题和牛客那版题目类似,不需要取模。