[leetcode]873. Length of Longest Fibonacci Subsequence
阿新 • • 發佈:2018-12-20
[leetcode]873. Length of Longest Fibonacci Subsequence
Analysis
中午吃啥—— [每天刷題並不難0.0]
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].)
Explanation:
第一種方法時間複雜度是O(n^2logm), m=A[i]+A[j]。
第二種方法動歸解決,時間複雜度是O(n^2)。
Implement
方法一:
class Solution {
public:
int lenLongestFibSubseq(vector<int>& A) {
unordered_set<int> nums(A.begin(), A.end());
int res = 0;
int len;
int a, b;
for(int i=0; i<A.size(); i++){
for(int j=i+1; j<A.size(); j+ +){
a = A[i];
b = A[j];
len = 2;
while(nums.count(a+b)){
b = a+b;
a = b-a;
len++;
}
res = max(res, len);
}
}
return res>2?res:0;
}
};
方法二:
class Solution {
public:
int lenLongestFibSubseq(vector<int>& A) {
int len = A.size();
int res = 0;
vector<vector<int>> dp(len, vector<int>(len, 2));
map<int, int> idx;
for(int i=0; i<len; i++)
idx[A[i]] = i;
for(int j=1; j<len; j++){
for(int i=0; i<j; i++){
if(idx.find(A[j]-A[i]) != idx.end() && idx[A[j]-A[i]] < i){
int tmp = idx[A[j]-A[i]];
dp[i][j] = max(dp[i][j], dp[tmp][i]+1);
}
}
}
for(int i=0; i<len; i++){
for(int j=i+1; j<len; j++)
res = max(res, dp[i][j]);
}
return res>2?res:0;
}
};