[动态规划] leetcode 1027 Longest Arithmetic Sequence

Posted fish1996

tags:

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

problem:https://leetcode.com/problems/longest-arithmetic-sequence/description/

        最长子序列类型问题。因为状态比较多,可以存在hash表里,之后直接查找。

class Solution {
public:
    int longestArithSeqLength(vector<int>& A) {
        vector<unordered_map<int,int>> dp(A.size());
        int n=A.size();
        int res=2;
        for(int i=0;i<n;i++){
            for(int j=0;j<i;j++){
                int d=A[i]-A[j];
                if(dp[j].find(d)==dp[j].end()){
                    dp[i][d]=2;
                }
                else{
                    dp[i][d]=dp[j][d]+1;
                }
                res=max(res,dp[i][d]);
            }
        }
        return res;
    }
};

 

以上是关于[动态规划] leetcode 1027 Longest Arithmetic Sequence的主要内容,如果未能解决你的问题,请参考以下文章