当前位置:网站首页>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;
}
}
边栏推荐
- 权限问题:source .bash_profile permission denied
- 【DesignMode】组合模式(composite mode)
- Basic introduction and source code analysis of webrtc threads
- NSSA area where OSPF is configured for Huawei equipment
- Single merchant v4.4 has the same original intention and strength!
- After summarizing more than 800 kubectl aliases, I'm no longer afraid that I can't remember commands!
- 2022.7.5-----leetcode. seven hundred and twenty-nine
- An understanding of & array names
- notepad++正则表达式替换字符串
- 免费的聊天机器人API
猜你喜欢
How much do you know about the bank deposit business that software test engineers must know?
STM32 configuration after chip replacement and possible errors
What are Yunna's fixed asset management systems?
There is no network after configuring the agent by capturing packets with Fiddler mobile phones
Gd32f4xx UIP protocol stack migration record
Intranet Security Learning (V) -- domain horizontal: SPN & RDP & Cobalt strike
Yunna | what are the main operating processes of the fixed assets management system
FFMPEG关键结构体——AVFrame
免费的聊天机器人API
Ffmpeg learning - core module
随机推荐
Pointer pointer array, array pointer
Analysis of the combination of small program technology advantages and industrial Internet
数据分析思维分析方法和业务知识——分析方法(三)
JS can really prohibit constant modification this time!
What are Yunna's fixed asset management systems?
LeetCode 斐波那契序列
JS 这次真的可以禁止常量修改了!
AtCoder Beginner Contest 258【比赛记录】
uniapp开发,打包成H5部署到服务器
Tools to improve work efficiency: the idea of SQL batch generation tools
电机的简介
Global and Chinese markets of POM plastic gears 2022-2028: Research Report on technology, participants, trends, market size and share
《编程之美》读书笔记
Single merchant v4.4 has the same original intention and strength!
The global and Chinese markets of dial indicator calipers 2022-2028: Research Report on technology, participants, trends, market size and share
选择致敬持续奋斗背后的精神——对话威尔价值观【第四期】
Permission problem: source bash_ profile permission denied
MySql——CRUD
wx.getLocation(Object object)申请方法,最新版
Global and Chinese markets for hinged watertight doors 2022-2028: Research Report on technology, participants, trends, market size and share