# 【LeetCode】 1035. Uncrossed Lines ## Description > 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. > 我們在兩條不同的平行線上寫下分別(按照給定的順序)寫下數列A和B。 > 現在我們再加上連接線:一條直線在A[i]和B[j]上,當: > * A[i] == B[j]; > * 這條線不會和其他的連接線相交。 > 注意,即使只有在頂點連接也算是相交,也就是說,每個數字只能被一條連接線給使用。 > 回傳在以上條件,我們能夠畫出的連接線可能的最大數值。 ## Example: ![](https://i.imgur.com/nXwbau7.png) > 筆者:WTF 這圖也太大... ``` 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 <= A.length <= 500 * 1 <= B.length <= 500 * 1 <= A[i], B[i] <= 2000 ## Solution * 仔細想想之後,便可以發現這題就是LCS(longest common subsequence),因此可以用DP解。 * 同樣都可以想成,要刪掉某些數字/字母之後,讓兩個輸入變成一樣的,然後求長度。 * 將問題切割成子問題,也就是將連線的部分和剩餘的部分分開。 * 其遞迴式為: $$f[1][1]=same(1,1)\\ f[i][j]=max\{f[i-1][j-1]+same(i,j),f[i-1][j],f[i][j-1]\}$$ ### Code ```C++=1 class Solution { public: int maxUncrossedLines(vector<int>& A, vector<int>& B) { int sA = A.size(), sB = B.size(); vector<vector<int>> dp(sA + 1, vector<int>(sB + 1, 0)); for(int i = 0; i < sA; i++) for(int j = 0; j < sB; j++) if(A[i] == B[j]) dp[i + 1][j + 1] = dp[i][j] + 1; else dp[i + 1][j + 1] = max(dp[i + 1][j], dp[i][j + 1]); return dp[sA][sB]; } }; ``` ###### tags: `LeetCode` `C++`