题目描述
- 呃~说来尴尬,在简单题栽跟头了= = (超时)
- 一般来说,这玩意是递归教学题了。但实际上会有很多重复的冗余步骤,实际上用动态规划效率会更高
思路 & 代码
递归
class Solution {
public int fib(int n) {
if(n == 0 || n == 1){
return n;
}
return (fib(n - 1) + fib(n - 2)) % 1000000007;
}
}
动态规划
class Solution {
int[] ans = new int[101];
public int fib(int n) {
ans[0] = 0;
ans[1] = 1;
for(int i = 2; i <= n; i++){
ans[i] = ans[i - 1] + ans[i - 2];
ans[i] %= 1000000007;
}
return ans[n];
}
}
- O(n) & O(1) ,因为这道题实际上只要记录当前两个元素的状态即可,因此实际上可以用两个变量起到整个数组的作用。
class Solution {
public int fib(int n) {
int a = 0;
int b = 1;
int sum = 0;
for(int i = 1; i <= n; i++){
sum = (a + b) % 1000000007;
a = b;
b = sum;
}
return a;
}
}
二刷
class Solution {
public int fib(int n) {
int pre = 0, now = 1, next = 0;
for(int i = 1; i <= n; i++) {
next = (pre + now) % 1000000007;
pre = now;
now = next;
}
return pre;
}
}