动态规划May-25th “Uncrossed Lines (Python3)”

Posted 迪乐阅读

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了动态规划May-25th “Uncrossed Lines (Python3)”相关的知识,希望对你有一定的参考价值。

——


 五月,总结模板的日子.

Day 25  ——  Uncrossed Lines


不交叉的线


问题描述

We write the integers of  A  and  B  (in the order they are given) on two separate horizontal lines.
Now, we may draw connecting lines: a straight line connecting two numbers  A[i]  and  B[j]  such that:
  • A[i] == B[j];

  • The line we draw does not intersect any other connecting (non-horizontal) line.

Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line.
Return the maximum number of connecting lines we can draw in this way.
 
Example 1:
   
     
     
   
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.
Example 2:
   
     
     
   
Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2]
Output: 3
Example 3:
   
     
     
   
Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1]
Output: 2
Note:
  1. 1 <= A.length <= 500

  2. 1 <= B.length <= 500

  3. 1 <= A[i], B[i] <= 2000



解题思路  


动态规划
递推公式:
       设 A[0] ~ A[x] 与 B[0] ~ B[y] 的最大连线数为 f(x, y),那么对于任意位置的 f(i, j) 而言:
        从后往前遍历,可以得到 递推公式:
  • 如果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])
最后dp[0][0]就是最大的划线数量

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)”的主要内容,如果未能解决你的问题,请参考以下文章

[动态规划]Tak and Cards

hdu2602Bone Collector ——动态规划(0/1背包问题)

May 25. 2018 Week 21st Friday

挑战程序设计竞赛(算法和数据结构)——17.2 01背包问题(动态规划)的JAVA实现

LeetCode_22_Apr_2nd_Week

LeetCode_22_Apr_2nd_Week