使用 JavaScript 在陣列中查詢斐波那契數列
斐波那契數列
如果一個數列 X_1, X_2, ..., X_n 是斐波那契數列,則
n >= 3
對於所有的 i + 2 <= n,都有 X_i + X_{i+1} = X_{i+2}
問題
我們要求寫一個 JavaScript 函式,該函式以一個數字陣列 arr 作為第一個也是唯一的引數。我們的函式應該找到並返回在陣列 arr 中存在的、最長的斐波那契子數列的長度。
子數列是從另一個數列 arr 中派生的,方法是從 arr 中刪除任意數量的元素(包括不刪除),而不改變剩餘元素的順序。
例如,如果函式的輸入為
輸入
const arr = [1, 3, 7, 11, 14, 25, 39];
輸出
const output = 5;
輸出解釋
因為最長的斐波那契子數列為 [3, 11, 14, 25, 39]
以下是程式碼
例
const arr = [1, 3, 7, 11, 14, 25, 39];
const longestFibonacci = (arr = []) => {
const map = arr.reduce((acc, num, index) => {
acc[num] = index
return acc
}, {})
const memo = arr.map(() => arr.map(() => 0))
let max = 0
for(let i = 0; i < arr.length; i++) {
for(let j = i + 1; j < arr.length; j++) {
const a = arr[i]
const b = arr[j]
const index = map[b - a]
if(index < i) {
memo[i][j] = memo[index][i] + 1
}
max = Math.max(max, memo[i][j])
}
}
return max > 0 ? max + 2 : 0
};
console.log(longestFibonacci(arr));輸出
5
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP