LeetCode #718 Maximum Length of Repeated Subarray
来源:互联网 发布:it专业 编辑:程序博客网 时间:2024/05/29 12:37
题目
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: 3Explanation: The repeated subarray with maximum length is [3, 2, 1].
Note:
- 1 <= len(A), len(B) <= 1000
- 0 <= A[i], B[i] < 100
解题思路
使用动态规划的思想,一开始最容易想到的就是设 f[i]
为以数字 A[i]
为结尾的最大公共子串的长度。假设 A[i - 1]
在 B
中的位置为 j
,则有 f[i] = f[i - 1] + 1
当且仅当 A[i - 1] == B[j - 1]
。显然,我们必须考虑 A
中的元素在 B
中的位置这一个约束,因此需要把动态规划的数组加多一个维度:令 f[i][j]
表示以 A[i]
或 B[j]
为结尾的最大公共子串的长度(A[i] == B[j]
时才有效),这样状态转移方程就出来了:
最后,求得
在实现的过程中,为了防止
i - 1
和 j - 1
导致数组下标溢出,且为了初始化的方便,我们让 i
和 j
从 1
开始计数,而 dp[0][j] = 0
且 dp[i][0] = 0
( dp[0][j] = 0
表示 A
数组中没有一个数字去和 B
中的数字匹配,dp[i][0]
同理)。C++代码实现
class Solution {public: int findLength(vector<int>& A, vector<int>& B) { int m = A.size(), n = B.size(); int rst = 0; int dp[1000 + 1][1000 + 1] = { 0 }; for (int i = 0; i <= m; ++i) { for (int j = 0; j <= n; ++j) { if (i == 0 || j == 0) { continue; } if (A[i - 1] == B[j - 1]) { dp[i][j] = dp[i - 1][j - 1] + 1; rst = max(dp[i][j], rst); } } } return rst; }};
阅读全文
0 0
- leetcode 718( Maximum Length of Repeated Subarray)
- LeetCode #718 Maximum Length of Repeated Subarray
- Leetcode 718 Maximum Length of Repeated Subarray
- Leetcode 718. Maximum Length of Repeated Subarray
- Leetcode | Maximum Length of Repeated Subarray
- Leetcode | Maximum Length of Repeated Subarray
- LeetCode:Maximum Length of Repeated Subarray
- [leetcode]Maximum Length of Repeated Subarray
- Leetcode 718. Maximum Length of Repeated Subarray
- leetcode 718. Maximum Length of Repeated Subarray
- [LeetCode]718. Maximum Length of Repeated Subarray
- [LeetCode]Maximum Length of Repeated Subarray
- [LeetCode] 718. Maximum Length of Repeated Subarray
- [leetcode] 718. Maximum Length of Repeated Subarray
- LeetCode:Maximum Length of Repeated Subarray
- leetCode-Maximum Length of Repeated Subarray
- Leetcode:718. Maximum Length of Repeated Subarray
- LeetCode#718 Maximum Length of Repeated Subarray (week9)
- Java并发编程:深入剖析ThreadLocal
- 阶层1
- 关于Python里面协程的一些理解
- ChibiOS/RT移植到STM32F407
- Codeforces 770D Draw Brackets! 模拟+中缀表达式
- LeetCode #718 Maximum Length of Repeated Subarray
- 20171104-程序员的自我修养
- C++动态内存管理(比较C动态内存管理)
- android下载解析xml
- GPIO口超强总结
- [bzoj4356][ceoi2014] wall
- PS之卡通徽章制作
- docker container DNS配置介绍和源码分析
- 链表倒序