您的位置:首页 > 其它

Maximum Length of Repeated Subarray解题报告

2017-11-05 10:19 453 查看
题目链接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


简单来说,就是求两个数组的最长公共子数组的长度。容易想到用动态规划来解决。将问题看成是求公共子数组中分别以
A[i],B[j]
结尾的数组最大长度。其中
0 <= i < len(A); 0 <= j < len(B)


设dp[i][j]是以A[i],B[j]结尾的公共子数组的最大长度。在上面的例子中dp[0][2] = 1, dp[4][2] = 3 dp[4][3] = 0


这样自然得到一个二维的动态规划方程:

if A[i] == B[j]
dp[i][j] = dp[i-1][j-1] + 1
else
dp[i][j] = 0


然后二维数组的最大值就是问题的解了

C++实现代码

class Solution {
public:
int findLength(vector<int>& A, vector<int>& B) {
int len1 = A.size();
int len2 = B.size();
int max = 0;
if(len1 == 0 || len2 == 0){
return 0;
}
int **dp = new int*[len1];
for(int i = 0; i < len1; i++){
dp[i] = new int[len2];
for(int j = 0; j < len2; j++){
dp[i][j] = 0;
}
}

for(int i = 0; i < len1; i++){
for(int j = 0; j < len2; j++){
if(i == 0 || j == 0){
if(A[i] == B[j]){
dp[i][j] = 1;
}
}else{
if(A[i] == B[j]){
dp[i][j] = dp[i-1][j-1] + 1;//动态规划方程
}
}
max = dp[i][j] > max ? dp[i][j] : max;
}
}
return max;
}
};


实现过程中涉及到二维数组的初始化和处理下标等细节问题,不过算法的核心就是那个动态规划方程。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: