题目需求
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部分还有很多更好的解题思路,包括了剪枝的部分。
但是我找到最简单易懂的是上面的代码。更优秀的解决方法等以后有基础再看吧。路艰且长,行则将至。