873. Length of Longest Fibonacci Subsequence
思路:起始点由两个点构成,所以有O(n2)种不同的起始点,然后在判断集合中是否存在前两项的和。
class Solution {
public int lenLongestFibSubseq(int[] A) {
if(A.length<=2)
return 0;
Set<Integer> set=new HashSet<Integer>();
for(int i=0;i<A.length;i++)
set.add(A[i]);
int max=2;
for(int i=0;i<A.length-2;i++){
for(int j=i+1;j<A.length-1;j++){
int temp0=A[i];
int temp1=A[j];
int cnt=2;
while(set.contains(temp0+temp1)){
cnt++;
temp1=temp0+temp1;
temp0=temp1-temp0;
}
max=Math.max(cnt,max);
}
}
return max==2?0:max;
}
}