Maximum Length of Repeated Subarray
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].
二维DP -> 制表
初始化 (其余空为0)
B\A | 1 | 2 | 3 | 2 | 1 |
---|---|---|---|---|---|
3 | 0 | 0 | 1 | 0 | 0 |
2 | 0 | ||||
1 | 1 | ||||
4 | 0 | ||||
7 | 0 |
递推式:dp[i][j] = dp[i-1][j-1] + 1 if A[j]==B[i]
自底向上,递推填表
B\A | 1 | 2 | 3 | 2 | 1 |
---|---|---|---|---|---|
3 | 0 | 0 | 1 | 0 | 0 |
2 | 0 | 0+1 | 0 | 1+1 | 0 |
1 | 1 | ||||
4 | 0 | ||||
7 | 0 |
ans = 表中最大值
//leetcode 718 DP 最长重复子数组
#include <bits/stdc++.h>
using namespace std;
int dp[1010][1010];
int findLength(vector<int>& A, vector<int>& B)
{
int lena = A.size(),lenb = B.size();
memset(dp, 0, sizeof(dp));
for(int i=0; i<lenb; i++)
{
if(A[0] == B[i])
dp[i][0] = 1;
}
for(int j=0; j<lena; j++)
{
if(A[j] == B[0])
dp[0][j] = 1;
}
int ans = 0;
for(int i=1; i<lena; i++)
{
for(int j=1; j<lenb; j++)
{
if(B[i] == A[j])
{
dp[i][j] = dp[i-1][j-1] + 1;
}
//cout<<dp[i][j]<<"--";
ans = max(ans, dp[i][j]);
}
//cout<<endl;
}
return ans;
}
int main()
{
vector<int> a = {0,0,0,0,1};
vector<int> b = {1,0,0,0,0};
cout<<findLength(a,b);
return 0;
}