动态规划May-25th “Uncrossed Lines (Python3)”
Posted 迪乐阅读
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了动态规划May-25th “Uncrossed Lines (Python3)”相关的知识,希望对你有一定的参考价值。
——
A
and
B
(in the order they are given) on two separate horizontal lines.
A[i]
and
B[j]
such that:
A[i] == B[j]
;The line we draw does not intersect any other connecting (non-horizontal) line.
Input: A = [1,4,2], B = [1,2,4]
Output: 2
Explanation: We can draw 2 uncrossed lines as in the diagram.
We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2.
Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2]
Output: 3
Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1]
Output: 2
1 <= A.length <= 500
1 <= B.length <= 500
1 <= A[i], B[i] <= 2000
-
如果A[i] == B[j] -> dp_table[i][j] = dp_table[i+1][j+1] + 1 -
否则 -> dp_table[i][j] = max(dp_table[i+1][j], dp_table[i][j+1])
class Solution:
def maxUncrossedLines(self, A: List[int], B: List[int]) -> int:
M, N = len(A), len(B)
dp_table = [[0] * (N + 1) for _ in range(M + 1)]
for i in range(M)[::-1]:
for j in range(N)[::-1]:
if A[i] == B[j]:
dp_table[i][j] = dp_table[i+1][j+1] + 1
else:
dp_table[i][j] = max(dp_table[i+1][j], dp_table[i][j+1])
return dp_table[0][0]
以上是关于动态规划May-25th “Uncrossed Lines (Python3)”的主要内容,如果未能解决你的问题,请参考以下文章
hdu2602Bone Collector ——动态规划(0/1背包问题)