-
Notifications
You must be signed in to change notification settings - Fork 43
/
length-of-longest-fibonacci-subsequence.py
65 lines (62 loc) · 1.79 KB
/
length-of-longest-fibonacci-subsequence.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# V0
# V1
# http://bookshadow.com/weblog/2018/07/22/leetcode-length-of-longest-fibonacci-subsequence/
# IDEA : DP
# STATUS EQ : dp[y][x + y] = max(dp[y][x + y], dp[x][y] + 1)
class Solution(object):
def lenLongestFibSubseq(self, A):
"""
:type A: List[int]
:rtype: int
"""
vset = set(A)
dp = collections.defaultdict(lambda: collections.defaultdict(int))
size = len(A)
ans = 0
for i in range(size):
x = A[i]
for j in range(i + 1, size):
y = A[j]
if x + y not in vset: continue
dp[y][x + y] = max(dp[y][x + y], dp[x][y] + 1)
ans = max(dp[y][x + y], ans)
return ans and ans + 2 or 0
# V1'
# https://blog.csdn.net/fuxuemingzhu/article/details/82715323
# IDEA : GREEDY
class Solution(object):
def lenLongestFibSubseq(self, A):
"""
:type A: List[int]
:rtype: int
"""
s = set(A)
n = len(A)
res = 0
for i in range(n - 1):
for j in range(i + 1, n):
a, b = A[i], A[j]
count = 2
while a + b in s:
a, b = b, a + b
count += 1
res = max(res, count)
return res if res > 2 else 0
# V2
# Time: O(n^2)
# Space: O(n)
class Solution(object):
def lenLongestFibSubseq(self, A):
"""
:type A: List[int]
:rtype: int
"""
lookup = set(A)
result = 2
for i in range(len(A)):
for j in range(i+1, len(A)):
x, y, l = A[i], A[j], 2
while x+y in lookup:
x, y, l = y, x+y, l+1
result = max(result, l)
return result if result > 2 else 0