剑指 Offer 10- I. 斐波那契数列
题目:
思路:
递归肯定是不行的,重复计算,将前n-1 和 n-2的值保存起来fori 计算即可。没有审题清楚,没有取模导致一直提交失败,还有取模的位置,要在相加后取模
代码:
class Solution {
//0,1,1,2,3,5,8,13,21,34,55...
public int fib(int n) {
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
//return fib(n - 1) + fib(n - 2);
int s1 = 1;
int s2 = 0;
int temp = s1;
for (int i = 2; i <= n; i++) {
temp = s1;
s1 = (s1 + s2) % 1000000007;
s2 = temp;
}
return s1;
}
}
跳青蛙也是类似的,就是多计算了一位
class Solution {
public int numWays(int n) {
if(n == 0) return 1;
int s1 = 1;
int s2 = 0;
int temp = s1;
for (int i = 1; i <= n; i++) {
temp = s1;
s1 = (s1 + s2) % 1000000007;
s2 = temp;
}
return s1;
}
}