From fe1c2aadfabf462c910e4989aa0c7c96f0560243 Mon Sep 17 00:00:00 2001 From: Baturu <45113401+z80160280@users.noreply.github.com> Date: Mon, 7 Jun 2021 22:47:00 -0700 Subject: [PATCH] =?UTF-8?q?Update=200718.=E6=9C=80=E9=95=BF=E9=87=8D?= =?UTF-8?q?=E5=A4=8D=E5=AD=90=E6=95=B0=E7=BB=84.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0718.最长重复子数组.md | 30 ++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0718.最长重复子数组.md b/problems/0718.最长重复子数组.md index be9109b2..204a513b 100644 --- a/problems/0718.最长重复子数组.md +++ b/problems/0718.最长重复子数组.md @@ -158,6 +158,36 @@ Java: Python: +> 动态规划: +```python +class Solution: + def findLength(self, A: List[int], B: List[int]) -> int: + dp = [[0] * (len(B)+1) for _ in range(len(A)+1)] + result = 0 + for i in range(1, len(A)+1): + for j in range(1, len(B)+1): + if A[i-1] == B[j-1]: + dp[i][j] = dp[i-1][j-1] + 1 + result = max(result, dp[i][j]) + return result +``` + +> 动态规划:滚动数组 +```python +class Solution: + def findLength(self, A: List[int], B: List[int]) -> int: + dp = [0] * (len(B) + 1) + result = 0 + for i in range(1, len(A)+1): + for j in range(len(B), 0, -1): + if A[i-1] == B[j-1]: + dp[j] = dp[j-1] + 1 + else: + dp[j] = 0 #注意这里不相等的时候要有赋0的操作 + result = max(result, dp[j]) + return result +``` + Go: ```Go