dp问题,一维是没法dp的,因为我们还要记录一个diff才能判断是否是Arithmetic Sequence。
dp[i][diff] 表示以 A[i] 结尾,等差为 diff 的最大长度。从这种角度来看本题和 LeetCode 300. Longest Increasing Subsequence / 354. Russian Doll Envelopes 极为相似。
class Solution { public: int longestArithSeqLength(vector<int>& A) { int n=A.size(); if (n<=1) return n; vector<unordered_map<int,int>> dp(n); int res=0; for (int i=0;i<n;++i){ for (int j=0;j<i;++j){ int diff=A[i]-A[j]; if (dp[j].count(diff)) dp[i][diff] = max(dp[i][diff], dp[j][diff]+1); else dp[i][diff] = 2; res = max(res,dp[i][diff]); } } return res; } };
原文地址:https://www.cnblogs.com/hankunyan/p/11456719.html
时间: 2024-11-05 20:47:59