当前位置:网站首页>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;
}
}
边栏推荐
- Single merchant v4.4 has the same original intention and strength!
- 时间戳的拓展及应用实例
- SQLServer连接数据库读取中文乱码问题解决
- Configuring OSPF GR features for Huawei devices
- Calculate sha256 value of data or file based on crypto++
- Hardware and interface learning summary
- DEJA_VU3D - Cesium功能集 之 055-国内外各厂商地图服务地址汇总说明
- Go learning - dependency injection
- What are the functions of Yunna fixed assets management system?
- notepad++正則錶達式替換字符串
猜你喜欢
MySql——CRUD
提升工作效率工具:SQL批量生成工具思想
wx.getLocation(Object object)申请方法,最新版
Problems encountered in the database
XML Configuration File
Recognize the small experiment of extracting and displaying Mel spectrum (observe the difference between different y_axis and x_axis)
How to solve the problems caused by the import process of ecology9.0
FPGA内部硬件结构与代码的关系
[noi simulation] Anaid's tree (Mobius inversion, exponential generating function, Ehrlich sieve, virtual tree)
Hudi of data Lake (2): Hudi compilation
随机推荐
MDK debug时设置数据实时更新
Huawei equipment configuration ospf-bgp linkage
【EI会议分享】2022年第三届智能制造与自动化前沿国际会议(CFIMA 2022)
SQLServer连接数据库读取中文乱码问题解决
多线程与高并发(8)—— 从CountDownLatch总结AQS共享锁(三周年打卡)
Priority queue (heap)
Date类中日期转成指定字符串出现的问题及解决方法
Codeforces gr19 D (think more about why the first-hand value range is 100, JLS yyds)
LeetCode 1598. Folder operation log collector
MySql——CRUD
Extension and application of timestamp
Global and Chinese markets for hinged watertight doors 2022-2028: Research Report on technology, participants, trends, market size and share
AtCoder Beginner Contest 258【比赛记录】
OpenCV经典100题
FFmpeg抓取RTSP图像进行图像分析
Configuring OSPF GR features for Huawei devices
[noi simulation] Anaid's tree (Mobius inversion, exponential generating function, Ehrlich sieve, virtual tree)
Key structure of ffmpeg -- AVCodecContext
OS i/o devices and device controllers
FFMPEG关键结构体——AVCodecContext