[leetcode-718-Maximum Length of Repeated Subarray]
Given two integer arrays A
and B
, return the maximum length of an subarray that appears in both arrays.
Example 1:
Input: A: [1,2,3,2,1] B: [3,2,1,4,7] Output: 3 Explanation: The repeated subarray with maximum length is [3, 2, 1].
Note:
- 1 <= len(A), len(B) <= 1000
- 0 <= A[i], B[i] < 100
思路:
动态规划,dp[i][j]代表长度为i的a与长度为j的b 出现相同的子数组的长度值。
如果a[i-1]==b[j-1] dp[i][j] = dp[i-1][j-1]+1;
int findLength(vector<int>& A, vector<int>& B) { int m = A.size(), n = B.size(); vector<vector<int>>dp(m + 1, vector<int>(n + 1, 0)); int ret = 0; for (int i = 0; i <= m;i++) { for (int j = 0; j <= n;j++) { if (i != 0 &&j != 0) { if (A[i - 1] == B[j - 1]) { dp[i][j] = 1 + dp[i - 1][j - 1]; ret = max(ret, dp[i][j]); } } else dp[i][j] = 0; } } return ret; }