当前位置:网站首页>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;
}
}
边栏推荐
- 7.5模拟赛总结
- Hudi of data Lake (2): Hudi compilation
- Codeforces Round #804 (Div. 2)【比赛记录】
- AtCoder Beginner Contest 254【VP记录】
- 【QT】Qt使用QJson生成json文件并保存
- Yunna | what are the main operating processes of the fixed assets management system
- 剖面测量之提取剖面数据
- OS i/o devices and device controllers
- Mathematical model Lotka Volterra
- 行列式学习笔记(一)
猜你喜欢
Hardware and interface learning summary
Teach you to run uni app with simulator on hbuilderx, conscience teaching!!!
Priority queue (heap)
About the slmgr command
[designmode] Decorator Pattern
How much do you know about the bank deposit business that software test engineers must know?
Date类中日期转成指定字符串出现的问题及解决方法
关于slmgr命令的那些事
[online chat] the original wechat applet can also reply to Facebook homepage messages!
Start from the bottom structure and learn the introduction of fpga---fifo IP core and its key parameters
随机推荐
wx. Getlocation (object object) application method, latest version
数据分析思维分析方法和业务知识——分析方法(二)
Pointer - character pointer
LeetCode 6005. The minimum operand to make an array an alternating array
anconda下载+添加清华+tensorflow 安装+No module named ‘tensorflow‘+KernelRestarter: restart failed,内核重启失败
OS i/o devices and device controllers
Leetcode 450 deleting nodes in a binary search tree
Gd32f4xx UIP protocol stack migration record
[EI conference sharing] the Third International Conference on intelligent manufacturing and automation frontier in 2022 (cfima 2022)
Huawei equipment configuration ospf-bgp linkage
Priority queue (heap)
Classic CTF topic about FTP protocol
Mysql - CRUD
Solve the problem of reading Chinese garbled code in sqlserver connection database
权限问题:source .bash_profile permission denied
What are Yunna's fixed asset management systems?
How much do you know about the bank deposit business that software test engineers must know?
【EI会议分享】2022年第三届智能制造与自动化前沿国际会议(CFIMA 2022)
Power query data format conversion, Split Merge extraction, delete duplicates, delete errors, transpose and reverse, perspective and reverse perspective
Global and Chinese market of valve institutions 2022-2028: Research Report on technology, participants, trends, market size and share