873. Length of Longest Fibonacci Subsequence

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
class Solution {
public int lenLongestFibSubseq(int[] arr) {
int n = arr.length;
int maxLength = 0;

// 定义 dp[j][k] 为以 arr[j], arr[k] 结尾的最长的斐波那契式子序列长度
int[][] dp = new int[n][n];

Map<Integer, Integer> numToIndexMap = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
numToIndexMap.put(arr[i], i);
}

for (int j = 1; j < n - 1; j++) {
for (int k = j + 1; k < n && j + 2 > maxLength; k++) {
int target = arr[k] - arr[j];
if (target >= arr[j]) {
// 剪枝
break;
}

Integer targetIndex = numToIndexMap.get(target);
if (targetIndex == null) {
continue;
}

dp[j][k] = Math.max(3, dp[targetIndex][j] + 1);
maxLength = Math.max(maxLength, dp[j][k]);
}
}

return maxLength;
}
}

References

873. Length of Longest Fibonacci Subsequence
剑指 Offer II 093. 最长斐波那契数列