LeetCode 1027. Longest Arithmetic Sequence

Posted 約束の空

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 1027. Longest Arithmetic Sequence相关的知识,希望对你有一定的参考价值。

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;
    }
};

 

以上是关于LeetCode 1027. Longest Arithmetic Sequence的主要内容,如果未能解决你的问题,请参考以下文章

leetcode1027. Longest Arithmetic Sequence

LeetCode Longest Palindrome

leetcode:longest words

Leetcode409. Longest Palindrome

leetcode:longest-increasing

[Leetcode]Longest Palindromic Substring