718. 最长重复子数组

dp[i][j] :以下标i - 1为结尾的A,和以下标j - 1为结尾的B,最长重复子数组长度为dp[i][j]。
dp[i][j] = dp[i - 1][j - 1] + 1;

image.png

  1. class Solution {
  2. public:
  3. int findLength(vector<int>& A, vector<int>& B) {
  4. vector<vector<int>> dp (A.size() + 1, vector<int>(B.size() + 1, 0));
  5. int result = 0;
  6. for (int i = 1; i <= A.size(); i++) {
  7. for (int j = 1; j <= B.size(); j++) {
  8. if (A[i - 1] == B[j - 1]) {
  9. dp[i][j] = dp[i - 1][j - 1] + 1;
  10. }
  11. if (dp[i][j] > result) result = dp[i][j];
  12. }
  13. }
  14. return result;
  15. }
  16. };