题意
求一个序列的最长的fibonacci子序列
方法
二维DP, 以 i和j 作为最后两个数字的fibonacci子序列的最大长度
代码
class Solution {
public:
int lenLongestFibSubseq(vector<int>& arr) {
unordered_map<int, int> indices;
int n = arr.size();
for (int i = 0; i < n; i++) {
indices[arr[i]] = i;
}
vector<vector<int>> dp(n, vector<int>(n));
int ans = 0;
for (int i = 0; i < n; i++) {
for (int j = i - 1; j >= 0 && arr[j] * 2 > arr[i]; j--) {
int k = -1;
if (indices.count(arr[i] - arr[j])) {
k = indices[arr[i] - arr[j]];
}
if (k >= 0) {
dp[j][i] = max(dp[k][j] + 1, 3);
}
ans = max(ans, dp[j][i]);
}
}
return ans;
}
};