[Leetcode]873. Length of Longest Fibonacci Subsequence

题目需求

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].

Links:https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/

题意理解

就是要求给定数组可以构成的最长fibonacci-like数列

解题思路

在Discussion里面看了半天,终于找到一种简洁的易懂的方法。分享给各位。方法是使用动态规划。
考虑以[a, b]为开始元素的fibonacci-like数列, 它的第三个元素应该为a+b(根据fibonacci数列的定义)。
假设dp[a, b]代表以[a, b]结束的fibonacci-like数列长度,则有:
d p [ a , b ] = m a x ( d p [ b , a + b ] + 1 , 2 ) dp[a, b] = max(dp[b, a+b]+1, 2) dp[a,b]=max(dp[b,a+b]+1,2)
这样思路就出来了,下面是代码。

解题代码

class Solution(object):
    def lenLongestFibSubseq(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        s, res = set(A), 2
        for i in range(len(A)-1):   
            for j in range(i+1, len(A)):
                a, b, l = A[i], A[j], 2
                while a+b in s:
                    a, b, l = b, a+b, l+1
                res = max(res, l)
        return res if res > 2 else 0

我是参考(抄)的这位老哥的。https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/discuss/152343/C%2B%2BJavaPython-Check-Pair

结语

基础不够,所以一开始只能参考别人的代码。Discussion部分还有很多更好的解题思路,包括了剪枝的部分。
但是我找到最简单易懂的是上面的代码。更优秀的解决方法等以后有基础再看吧。路艰且长,行则将至。

END

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值