题目
分析
用递归就错了,肯定回超出时间限制,用迭代会更好
代码
//超出时间限制
class Solution {
public int fib(int n) {
if (n<2) {
return n;
}
int first = fib(n - 1) % 1000000007;
int second = fib(n - 2) % 1000000007;
return (first + second) % 1000000007;
}
}
class Solution {
public int fib(int n) {
if(n<2) return n;
int now = 0;
int first = 0;
int second = 1;
for(int i = 1;i<n;i++) {
now = (first + second) % 1000000007;
first = second;
second = now;
}
return now;
}
}
//青蛙跳台阶
class Solution {
public int numWays(int n) {
int now = 0;
if(n==0) now=1;
if(n==1) now=1;
if(n>1){
int first = 1;
int second = 1;
for(int i = 1;i<n;i++) {
now = (first + second) % 1000000007;
first = second;
second = now;
}
}
return now;
}
}