Leetcode 873:最长递增斐波那契子序列

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].
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++.)
解法1:
遍历A的每个值i,以及i之后的每个值j,固定i,j,并放进一个list里面:sub = [A[i],A[j]],不断判断sub的最后两个数的和是否存在A中,如果存在,把这两个数的和继续存进sub中,如果不存在,则遍历下一个j.

class Solution:
    def lenLongestFibSubseq(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        lena = len(A)
        s = set(A)
        outut = []
        length = 2
        for i in range(lena):
            for j in range(i+1,lena):
                sub = [A[i],A[j]]
                while (sub[-1]+sub[-2] in s):
                    sub.append(sub[-1]+sub[-2])
                if len(sub) > length:
                    length = len(sub)
                    output = sub
        if (length>2):
            return length
        else:
            return 0

解法2:
动态规划,以位置所在的值作为dp的key,遍历所有值,并在每个值i的前面所有值j遍历,找出A[i]-A[j]是否存在,若存在,则找到该值的位置A[i]-A[j],以(A[i]-A[j],A[j])作为第i个值之前的第j个值的序列,因此有状态转移方程dp[(A[j],A[i])] = dp[(A[i]-A[j],A[j])] + 1;当(A[i]-A[j],A[j])不存在dp中时,说明(A[i]-A[j],A[j])不构成斐波那契数列,此两个数加上A[i]总共三个数,所以此时dp[(A[j],A[i])] = 3

class Solution:
    def lenLongestFibSubseq(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        s = set()
        dp = {}
        for i in range(len(A)):
            s.add(A[i])
            for j in range(i):
                 if A[i]-A[j] in s and A[i]-A[j]<A[j]:
                     if (A[i]-A[j],A[j]) in dp:
                         dp[(A[j],A[i])] = dp[(A[i]-A[j],A[j])] + 1
                     else:
                         dp[(A[j],A[i])] = 3
        return max(dp.values()) if dp else 0

猜你喜欢

转载自blog.csdn.net/Flying_sfeng/article/details/82814051