前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【DP】873. Length of Longest Fibonacci Subsequence

【DP】873. Length of Longest Fibonacci Subsequence

作者头像
echobingo
发布2019-06-02 15:04:28
3600
发布2019-06-02 15:04:28
举报
题目描述:

A sequence X_1, X_2, ..., X_n is fibonacci-like if:

  • n >= 3
  • X_i + X_{i+1} = X_{i+2} for all i + 2 <= n

Given a strictly increasing array A of positive integers forming a sequence, find the length of the longest fibonacci-like subsequence of A. If one does not exist, return 0.

(Recall that a subsequence is derived from another sequence A by deleting any number of elements (including none) from A, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].)

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].
解题思路:

这道题是求最长斐波那契子序列,做法:

  • 两层 for 循环,得到斐波那契的前两个数 first 和 second;
  • 判断这两个数的和(第三个数)third 是否在数组中;
  • 如果 third 在数组中,斐波那契三个数整体前进一步,即更新这三个数: first = second, second = third, third = first + second,长度加 1,然后回到上一步继续判断;
  • 如果 third 不在数组中,更新最大长度的值。

注意:在编程的时候,数组转化为集合 set,可以使判断 third 的时间复杂度为 O(1)。

时间复杂度为 O((N^2) * logM),log M 来自于循环判断 third 是否在数组中;空间复杂度为 O(N),即开辟集合 set 所占大小。

Python3 实现:
class Solution:
    def lenLongestFibSubseq(self, A: List[int]) -> int:
        setA = set(A)
        ans = 0
        for i in range(len(A)):
            for j in range(i+1, len(A)):
                first, second = A[i], A[j]
                third = first + second
                length = 2
                while third in setA:  # 当 third 在数组中,更新三个值继续判断
                    length += 1
                    first = second
                    second = third
                    third = first + second
                ans = max(ans, length)  # 更新最大长度
        return ans if ans >= 3 else 0
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.06.01 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述:
    • Example 1:
      • Example 2:
      • 解题思路:
      • Python3 实现:
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档