[动态规划] 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;
    }
};

猜你喜欢

转载自www.cnblogs.com/fish1996/p/11324762.html
今日推荐