1. 题目
2. 思路
(1) 迭代
(2) 矩阵快速幂
3. 代码
public class Test {
public static void main(String[] args) {
}
}
class Solution {
public int fib(int n) {
if (n < 2) {
return n;
}
int n1 = 0;
int n2 = 0;
int res = 1;
while (n > 1) {
n1 = n2;
n2 = res;
res = (n1 + n2) % 1000000007;
n--;
}
return res;
}
}
class Solution1 {
public int fib(int n) {
if (n < 2) {
return n;
}
int[][] mat = {{1, 1}, {1, 0}};
int[][] res = pow(mat, n - 1);
return res[0][0];
}
private int[][] pow(int[][] mat, int n) {
int[][] res = {{1, 0}, {0, 1}};
while (n > 0) {
if ((n & 1) == 1) {
res = multiply(res, mat);
}
n >>= 1;
mat = multiply(mat, mat);
}
return res;
}
private int[][] multiply(int[][] mat1, int[][] mat2) {
int[][] res = new int[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
res[i][j] = (int) (((long) mat1[i][0] * mat2[0][j] + (long) mat1[i][1] * mat2[1][j]) % 1000000007);
}
}
return res;
}
}