说实话这个题第一眼不太容易想到用DP😂,但用DP确实是最简单的做法。
原理如下图:
代码
class Solution {
public:
int findLength(vector<int>& A, vector<int>& B) {
int maxLen = 0;
vector<vector<int>> f(A.size() + 1, vector<int>(B.size() + 1, 0)); //定义二维状态数组
for (int i = 1; i <= A.size(); i ++ )
for (int j = 1; j <= B.size(); j ++ )
{
if (A[i - 1] == B[j - 1])
f[i][j] = f[i - 1][j - 1] + 1; //当两个数相等时更新状态
if (f[i][j] > maxLen) maxLen = f[i][j]; //每次更新最长的重复子数组
}
return maxLen;
}
};