当前位置:网站首页>Leetcode Fibonacci sequence
Leetcode Fibonacci sequence
2022-07-06 00:23:00 【Stingy Wolf】
List of articles
Title Description
Write a function , Input n , Fibonacci, please (Fibonacci) The number of the sequence n term ( namely F(N)). Fibonacci series is defined as follows :
F(0) = 0, F(1) = 1
F(N) = F(N - 1) + F(N - 2), among N > 1.
The Fibonacci series is composed of 0 and 1 Start , The Fibonacci number after that is the sum of the two numbers before .
The answer needs to be modelled 1e9+7(1000000007), If the initial result of calculation is :1000000008, Please return 1.
Ideas
The most intuitive idea is recursion , as follows
class Solution {
public int fib(int n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
}
But recursion will cause a lot of double counting , Submission of the report timed out .
Dynamic programming
The recursion above is a top-down solution ( By solving F(n) Start , Solve recursively first F(n-1),… Until F(1)), We can add Memorization on the basis of recursion . You can also change the angle , Solve from the bottom up ( Solve first F(1), Solve again F(2), Finally, solve F(n)), So consider using dynamic programming , Remember to add modulo operation
class Solution {
int MOD = 1_000_000_000 + 7;
public int fib(int n) {
if (n <= 1) return n;
int[] f = new int[n + 1];
f[1] = 1;
for (int i = 2; i <= n; i++) f[i] = (f[i - 1] + f[i - 2]) % MOD;
return f[n];
}
}
The time complexity of dynamic programming is O ( n ) O(n) O(n)
Matrix fast power
Advanced approach can use matrix fast power , Reduce time complexity to O ( l o g n ) O(logn) O(logn)
Such a recursive relationship can be established by matrix multiplication :
[ 1 1 1 0 ] × [ F ( n ) F ( n − 1 ) ] = [ F ( n ) + F ( n − 1 ) F ( n ) ] = [ F ( n + 1 ) F ( n ) ] \left[ \begin{matrix} 1 & 1\\ 1 & 0\\ \end{matrix} \right ] \times \left[ \begin{matrix} F(n)\\ F(n-1) \end{matrix} \right] = \left[ \begin{matrix} F(n) + F(n-1)\\ F(n)\\ \end{matrix} \right ] = \left[ \begin{matrix} F(n+1)\\ F(n)\\ \end{matrix} \right ] [1110]×[F(n)F(n−1)]=[F(n)+F(n−1)F(n)]=[F(n+1)F(n)]
From this we can deduce , The following relationship
[ 1 1 1 0 ] n − 1 × [ F ( 1 ) F ( 0 ) ] = [ F ( n ) F ( n − 1 ) ] \left[ \begin{matrix} 1 & 1\\ 1 & 0\\ \end{matrix} \right ] ^{n-1} \times \left[ \begin{matrix} F(1)\\ F(0) \end{matrix} \right] = \left[ \begin{matrix} F(n)\\ F(n - 1)\\ \end{matrix} \right ] [1110]n−1×[F(1)F(0)]=[F(n)F(n−1)]
So the problem turns into finding a matrix n The next power , And exponentiation , We can use fast power algorithm , Reduce time complexity to O ( l o g n ) O(logn) O(logn).
It's just the multiplication of two integers , It becomes the multiplication of two matrices . Notice in the matrix , Our initial matrix should be set to Unit matrix
[ 1 0 0 1 ] \left[ \begin{matrix} 1 & 0\\ 0 & 1\\ \end{matrix} \right ] [1001]
The identity matrix is multiplied by any matrix , Is equal to the multiplied matrix itself .
This identity matrix , It's equivalent to an integer 1,1 Multiplying by any number equals itself .
About matrix multiplication , I reviewed the basic knowledge of College linear algebra again . Yes 2 Matrix A and B,A Yes m That's ok ,n Column , call A It's a m × n m × n m×n Matrix ,B Yes n That's ok ,k Column , call B It's a n × k n × k n×k Matrix . Only when A Columns of , be equal to B The number of lines , These two matrices can be multiplied , The result of multiplication is C, It's a m × k m×k m×k Matrix . For the result matrix C No [i,j] Value of position , It is equal to matrix A Of the i That's ok , And matrices B Of the j Column , The result of multiplying and adding each element .
class Solution {
int MOD = 1_000_000_000 + 7;
public int fib(int n) {
if (n <= 1) return n;
int[][] matrix = {
{
1, 1}, {
1, 0}};
int[][] res = pow(matrix, n - 1);
// because F(1) = 1, Then the value of the first row and the first column of the final matrix , Namely F(n)
return res[0][0];
}
// Fast power algorithm
private int[][] pow(int[][] m, int p) {
int[][] res = {
{
1, 0}, {
0, 1}}; // Unit matrix , The identity matrix multiplied by any matrix is itself
while (p > 0) {
if ((p & 1) == 1) {
res = multi(res, m);
}
p >>= 1;
m = multi(m, m);
}
return res;
}
// 2 Matrix multiplication
private int[][] multi(int[][] matrix1, int[][] matrix2) {
int n1 = matrix1.length, m1 = matrix1[0].length;
int n2 = matrix2.length, m2 = matrix2[0].length;
if (m1 != n2) throw new IllegalArgumentException(" Cannot calculate matrix multiplication ");
// Matrix multiplication
int[][] res = new int[n1][m2];
for (int i = 0; i < n1; i++) {
for (int j = 0; j < m2; j++) {
for (int k = 0; k < m1; k++) {
res[i][j] = (int) ((res[i][j] + ((long)matrix1[i][k] * matrix2[k][j]) % MOD) % MOD);
}
}
}
return res;
}
}
边栏推荐
- What are the functions of Yunna fixed assets management system?
- Teach you to run uni app with simulator on hbuilderx, conscience teaching!!!
- Pointer pointer array, array pointer
- Go learning --- structure to map[string]interface{}
- Global and Chinese markets for pressure and temperature sensors 2022-2028: Research Report on technology, participants, trends, market size and share
- Shardingsphere source code analysis
- Ffmpeg captures RTSP images for image analysis
- wx. Getlocation (object object) application method, latest version
- 选择致敬持续奋斗背后的精神——对话威尔价值观【第四期】
- Notepad + + regular expression replace String
猜你喜欢

MDK debug时设置数据实时更新

硬件及接口学习总结

Mysql - CRUD

常用API类及异常体系

Configuring OSPF GR features for Huawei devices

XML配置文件

wx. Getlocation (object object) application method, latest version

Huawei equipment is configured with OSPF and BFD linkage

Room cannot create an SQLite connection to verify the queries

【EI会议分享】2022年第三届智能制造与自动化前沿国际会议(CFIMA 2022)
随机推荐
【EI会议分享】2022年第三届智能制造与自动化前沿国际会议(CFIMA 2022)
Choose to pay tribute to the spirit behind continuous struggle -- Dialogue will values [Issue 4]
Global and Chinese markets of POM plastic gears 2022-2028: Research Report on technology, participants, trends, market size and share
【NOI模拟赛】Anaid 的树(莫比乌斯反演,指数型生成函数,埃氏筛,虚树)
FFMPEG关键结构体——AVFormatContext
MySQL存储引擎
An understanding of & array names
[noi simulation] Anaid's tree (Mobius inversion, exponential generating function, Ehrlich sieve, virtual tree)
Uniapp development, packaged as H5 and deployed to the server
Recognize the small experiment of extracting and displaying Mel spectrum (observe the difference between different y_axis and x_axis)
MySql——CRUD
AtCoder Beginner Contest 254【VP记录】
剖面测量之提取剖面数据
Global and Chinese markets of universal milling machines 2022-2028: Research Report on technology, participants, trends, market size and share
如何利用Flutter框架开发运行小程序
【QT】Qt使用QJson生成json文件并保存
小程序技术优势与产业互联网相结合的分析
免费的聊天机器人API
7.5 simulation summary
常用API类及异常体系