来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/length-of-longest-fibonacci-subsequence 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

如果序列 X1, X_2, …, X_n 满足下列条件,就说它是 斐波那契式 的:
n >= 3
对于所有 i + 2 <= n,都有 X_i + X
{i+1} = X_{i+2}
给定一个严格递增的正整数数组形成序列 arr ,找到 arr 中最长的斐波那契式的子序列的长度。如果一个不存在,返回 0 。
(回想一下,子序列是从原序列 arr 中派生出来的,它从 arr 中删掉任意数量的元素(也可以不删),而不改变其余元素的顺序。例如, [3, 5, 8] 是 [3, 4, 5, 6, 7, 8] 的一个子序列)

解答

  1. /**
  2. * @param {number[]} arr
  3. * @return {number}
  4. */
  5. var lenLongestFibSubseq = function(arr) {
  6. if (!arr) return 0;
  7. const idxMap = new Map();
  8. for (let i = 0; i < arr.length; i++) {
  9. idxMap.set(arr[i], i);
  10. }
  11. let max = 0;
  12. for (let i = 0; i < (arr.length - 1); i++) {
  13. for (let j = i + 1; j < arr.length; j++) {
  14. let ref = { current: 2 };
  15. findFebonaci(arr, i, j, ref, idxMap);
  16. if (ref.current > 2) {
  17. max = Math.max(ref.current, max);
  18. }
  19. }
  20. }
  21. return max;
  22. };
  23. function findFebonaci (arr, i, j, ref, idxMap) {
  24. const nextValue = arr[i] + arr[j];
  25. const nextIndex = idxMap.get(nextValue);
  26. if (nextIndex !== undefined) {
  27. ref.current += 1;
  28. findFebonaci(arr, j, nextIndex, ref, idxMap);
  29. }
  30. }