力扣873 最长的斐波那契数列
873. 最长的斐波那契子序列的长度
如果序列 X_1, X_2, …, X_n 满足下列条件,就说它是 斐波那契式 的:
n >= 3
对于所有 i + 2 <= n,都有 Xi + X{i+1} = X_{i+2}
给定一个严格递增的正整数数组形成序列,找到 A 中最长的斐波那契式的子序列的长度。如果一个不存在,返回 0 。
(回想一下,子序列是从原序列 A 中派生出来的,它从 A 中删掉任意数量的元素(也可以不删),而不改变其余元素的顺序。例如, [3, 5, 8] 是 [3, 4, 5, 6, 7, 8] 的一个子序列)
示例 1:
输入: [1,2,3,4,5,6,7,8]
输出: 5
解释:
最长的斐波那契式子序列为:[1,2,3,5,8] 。
示例 2:
输入: [1,3,7,11,12,14,18]
输出: 3
解释:
最长的斐波那契式子序列有:
[1,11,12],[3,11,14] 以及 [7,11,18] 。
提示:
3 <= A.length <= 1000
1 <= A[0] < A[1] < … < A[A.length - 1] <= 10^9
(对于以 Java,C,C++,以及 C# 的提交,时间限制被减少了 50%)
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/length-of-longest-fibonacci-subsequence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
BF方法
class Solution {
public:
int lenLongestFibSubseq(vector<int>& arr) {
set<int>search;
for(auto &index : arr)
search.insert(index);
int size = arr.size();
int ret = 0;
for(int i = 0; i < size - 2; i++)
{
for(int j = i + 1; j < size - 1; j++)
{
int num_0 = arr[i];
int num_1 = arr[j];
int tmp = 0;
if(search.find(num_0 + num_1) != search.end())
{
tmp = 2;
while(search.find(num_0 + num_1) != search.end())
{
tmp++;
int next = num_0 + num_1;
num_0 = num_1;
num_1 = next;
}
}
ret = max(ret, tmp);
}
}
return ret;
}
};
官方
class Solution {
public:
int lenLongestFibSubseq(vector<int>& A) {
int N = A.size();
unordered_set<int> S(A.begin(), A.end());
int ans = 0;
for (int i = 0; i < N; ++i)
for (int j = i+1; j < N; ++j) {
/* With the starting pair (A[i], A[j]),
* y represents the future expected value in
* the fibonacci subsequence, and x represents
* the most current value found. */
int x = A[j], y = A[i] + A[j];
int length = 2;
while (S.find(y) != S.end()) {
int z = x + y;
x = y;
y = z;
ans = max(ans, ++length);
}
}
return ans >= 3 ? ans : 0;
}
};
采用动态规划的方法
class Solution {
public:
int lenLongestFibSubseq(vector<int>& arr) {
int N = arr.size();
unordered_map<int, int>index;
for(int i = 0; i < N; i++)
index[arr[i]] = i;
unordered_map<int, int>longest;
int ans = 0;
for(int k = 0; k < N; ++k)
{
for(int j = 0; j < k; ++j)
{
if(arr[k] - arr[j] < arr[j] && index.count(arr[k] - arr[j]))
{
int i = index[arr[k] - arr[j]];
longest[j * N + k] = longest[i * N + j] + 1;
ans = max(ans, longest[j * N + k] + 2);
}
}
}
return ans >= 3 ? ans : 0;
}
};