题目:
We write the integers of nums1
and nums2
(in the order they are given) on two separate horizontal lines.
Now, we may draw connecting lines: a straight line connecting two numbers nums1[i]
and nums2[j]
such that:
nums1[i] == nums2[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: nums1 = [1,4,2], nums2 = [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 nums1[1]=4 to nums2[2]=4 will intersect the line from nums1[2]=2 to nums2[1]=2.
Example 2:
Input: nums1 = [2,5,1,2,5], nums2 = [10,5,2,1,5,2]
Output: 3
Example 3:
Input: nums1 = [1,3,7,1,7,5], nums2 = [1,9,2,5,1]
Output: 2
Note:
1 <= nums1.length <= 500
1 <= nums2.length <= 500
1 <= nums1[i], nums2[i] <= 2000
思路:
如果用常规思路贪心的话很明显会错并且复杂度不好判断,这里显然当作字符串处理用DP。首先建立二维DP数组,初始化为0即可,假设最开始一对没有。之后从左到右从上到下遍历,设定row是A,col是B,那么当某A[i]和B[j]相等时,可以增加一种连法,否则当前格子的DP值就取左或者上的最大值即可。本题不是特别难,之要想清楚用DP即可。
代码:
class Solution {
public:
int maxUncrossedLines(vector<int>& A, vector<int>& B) {
vector<vector<int>> dp(A.size()+1, vector<int>(B.size()+1, 0));
for(int i = 0; i < A.size(); i++){
for(int j = 0; j < B.size(); j++){
if(A[i] == B[j]){
dp[i+1][j+1] = dp[i][j] + 1;
}else
dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j]);
}
}
return dp[A.size()][B.size()];
}
};