• 873. Length of Longest Fibonacci Subsequence


    问题:

    给定一个递增数组,求其中所包含的斐波那契数列的长度。

    A[i]+A[i+1]=A[i+2]

    Example 1:
    Input: [1,2,3,4,5,6,7,8]
    Output: 5
    Explanation:
    The longest subsequence that is fibonacci-like: [1,2,3,5,8].
    
    Example 2:
    Input: [1,3,7,11,12,14,18]
    Output: 3
    Explanation:
    The longest subsequence that is fibonacci-like:
    [1,11,12], [3,11,14] or [7,11,18].
     
    
    Note:
    3 <= A.length <= 1000
    1 <= A[0] < A[1] < ... < A[A.length - 1] <= 10^9
    (The time limit has been reduced by 50% for submissions in Java, C, and C++.)
    

      

    解法:

    遍历最开始的两个加数,b:i=1~size,a:j=0~i-1

    得出之和a+b,再在数列中查找是否存在这样的数,

    递归,使得b=a+b,a=原来的b,继续求和,直到找不到,得到到目前为止的数列长度l

    最终结果res=max(res,l)

    代码参考:

     1 class Solution {
     2 public:
     3     int lenLongestFibSubseq(vector<int>& A) {
     4         unordered_set<int>s(A.begin(), A.end());
     5         int res=0;
     6         for(int i=1; i<A.size(); i++){
     7             for(int j=0; j<i; j++){
     8                 int a=A[j], b=A[i], l=2;
     9                 while(s.count(a+b)){
    10                     l++;
    11                     b=a+b;
    12                     a=b-a;
    13                 }
    14                 res=max(res,l);
    15             }
    16         }
    17         return res>2?res:0;
    18     }
    19 };
  • 相关阅读:
    hibernate映射-单向多对一映射
    CSS
    HTML基础
    复习
    元类,单例
    数据类型,约束,存储引擎
    数据库概念,安装,基本操作
    IO模型
    异步回调,协程
    GIL锁,线程池,同步异步
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/12900103.html
Copyright © 2020-2023  润新知