[Leetcode Daily Question] 1027. Longest Arithmetic Sequence

I didn't think about it for a while at the beginning, but after reading the solution, I suddenly realized that I am still quite unfamiliar with two-dimensional dynamic programming, and I have to practice more

The solution is as follows

class Solution {
public:
    int longestArithSeqLength(vector<int>& nums) {
        int n = nums.size();
        int f[n][1001];
        memset(f,0,sizeof(f));
        int ans = 0;
        for(int i = 1;i < n; i++){
            for(int k = 0;k < i; k++){
                int j = nums[i] - nums[k] + 500;
                f[i][j] = max(f[i][j],f[k][j]+1);
                ans = max(ans,f[i][j]);
            }
        }
        return ans + 1;
    }
};

The planning recursion is

f[i][j] = max(f[i][j],f[k][j]+1);

j is the tolerance. Each corresponding element has a corresponding tolerance array from 0 to its own value. The essence of dp is to change space for time. The idea of ​​this question is to find the longest value of the tolerance array corresponding to each element, and then recursively ans , and then output it.

Guess you like

Origin blog.csdn.net/qq_63499305/article/details/130302069