[Dynamic Programming] leetcode 1027 Longest Arithmetic Sequence

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

        The longest subsequence type of problem. Because the state more, there can hash table, directly after the search.

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

 

Guess you like

Origin www.cnblogs.com/fish1996/p/11324762.html