problem: https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/
O(n2), 把已有的a + b = c 结果用hashmap存起来,然后计算当前数字为结尾的最长类斐波那契子序列。
其中,dp[i][j] 代表当前数字为第j个,上一个选择的数字为第i个。
class Solution { public: int lenLongestFibSubseq(vector<int>& A) { int n = A.size(); unordered_map<int, int> number; for(int i = 0;i < n;i++) { number[A[i]] = i; } vector<vector<pair<int,int>>> last(n); int maxnum = A.back(); for(int i = 0;i < n; i++) // begin { for(int j = i + 1;j < n; j++) // end { int num = A[i] + A[j]; if(num > maxnum) { break; } if(number.find(num) != number.end()) { last[number[num]].push_back({i, j}); } } } int res = 0; vector<vector<int>> dp(n, vector<int>(n, 0)); for(int i = 0;i < n;i++) { for(auto& k : last[i]) { dp[k.second][i] = max(dp[k.second][i], dp[k.first][k.second] + 1); res = max(res, dp[k.second][i]); } } if(res == 0) return 0; return res + 2; } };