1035. 不相交的線
阿新 • • 發佈:2021-05-23
題目連結:https://leetcode-cn.com/problems/uncrossed-lines/
思路:就是最長公共子序列(longest common sequence,LCS),dp入門題,不解釋了。
轉移公式:
上程式碼:
class Solution { fun maxUncrossedLines(nums1: IntArray, nums2: IntArray): Int { var result = 0 var dp = Array(size = nums1.size + 1, init = { IntArray(nums2.size + 1) }) for (i in 1..nums1.size) { for (j in 1..nums2.size) { if (nums1[i-1] == nums2[j-1]) { dp[i][j] = dp[i - 1][j - 1] + 1 } else { dp[i][j] = dp[i - 1][j].coerceAtLeast(dp[i][j - 1]) } result = result.coerceAtLeast(dp[i][j]) } } return result } }