码迷,mamicode.com
首页 > 编程语言 > 详细

718. 最长重复子数组. dp

时间:2020-07-03 01:17:50      阅读:94      评论:0      收藏:0      [点我收藏+]

标签:strong   str   problem   http   https   bar   mem   输入   for   

给两个整数数组?A?和?B?,返回两个数组中公共的、长度最长的子数组的长度。

示例 1:

输入:
A: [1,2,3,2,1]
B: [3,2,1,4,7]
输出: 3
解释:
长度最长的公共子数组是 [3, 2, 1]。
说明:

1 <= len(A), len(B) <= 1000
0 <= A[i], B[i] < 100

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-length-of-repeated-subarray
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

O(n*m)

class Solution {
public:
    int findLength(vector<int>& A, vector<int>& B) {
        int n = A.size(), m = B.size();
        int dp[n + 1][m + 1];
        int ans = 0;

        memset(dp, 0, sizeof(dp));
        for (int i = 1; i <= n; i++){
            for (int j = 1; j <= m; j++){
                if (A[i - 1] == B[j - 1]){
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                    ans = max(ans, dp[i][j]);
                }
            }
        }
        
        return ans;
    }
};


718. 最长重复子数组. dp

标签:strong   str   problem   http   https   bar   mem   输入   for   

原文地址:https://www.cnblogs.com/xgbt/p/13227809.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!