zoukankan      html  css  js  c++  java
  • Java实现 LeetCode 718 最长重复子数组(动态规划)

    718. 最长重复子数组

    给两个整数数组 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

    class Solution {
    
           public int findLength(int[] A, int[] B) {
            int[] dp = new int[B.length];
            int max = 0;
            for(int j = 0; j < B.length; j++) {
                if(A[0] == B[j]) {
                    dp[j] = 1;
                    max = 1;
                }
            }
    
            for(int i = 1; i < A.length; i++) {
                for(int j = B.length - 1; j > 0; j--) {
                    if(A[i] == B[j]) {
                        dp[j] = dp[j - 1] + 1;
                        if(dp[j] > max) {
                            max = dp[j];
                        }
                    } else {
                        dp[j] = 0;
                    }
                }
                dp[0] = (A[i] == B[0]) ? 1 : 0;
            }
            return max;   
        }
    
        //   public int findLength(int[] A, int[] B) {
        //     if (A == null || B == null) {
        //         return 0;
        //     }
        //     int res = 0;
        //     int[][] dp = new int[A.length + 1][B.length + 1];
        //     for (int i = 1; i < dp.length; i++) {
        //         for (int j = 1; j < dp[i].length; j++) {
        //             dp[i][j] = A[i - 1] == B[j - 1] ? dp[i - 1][j - 1] + 1 : 0;
        //             res = Math.max(res, dp[i][j]);
        //         }
        //     }
        //     return res;
        // }
        
    }
    
  • 相关阅读:
    Volume 6. Mathematical Concepts and Methods
    git帮助网址
    ubuntu 下安装wine
    ubuntu 通过ppa源安装mysql5.6
    ubuntu qq安装
    ubuntu14.04 fcitx安装
    language support图标消失
    ubuntu root用户登陆
    ubuntu 安装codeblocks13.12
    ubuntu tomcat自启动
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13074761.html
Copyright © 2011-2022 走看看