Longest Common Subsequence
Last updated
Was this helpful?
Last updated
Was this helpful?
Given two strings, find the longest common subsequence (LCS).
Your code should return the length of LCS.
What's the definition of Longest Common Subsequence?
For "ABCD" and "EDCA", the LCS is "A" (or "D", "C"), return 1.
For "ABCD" and "EACB", the LCS is "AC", return 2.
单序列型研究如何切,双序列型研究最后一个数字或者字母。
双序列型动态规划
图加上故事,非常有助于记忆。
abcd = abcd then f[i - 1][j - 1] + 1
state: f[i][j]代表了第一个sequence的前i个数字/字符,配上第二个sequence的前j个... function: f[i][j] =研究第i个和第j个的匹配关系 initialize: f[i][0]和f[0][i]
answer: f[s1.length()][s2.length()]
state: f[i][j]表示前i个字符配上前j个字符的LCS的长度 function: f[i][j] = MAX(f[i-1][j], f[i][j-1], f[i-1][j-1] + 1) // a[i] == b[j]
= MAX(f[i-1][j], f[i][j-1]) // a[i] != b[j] intialize: f[i][0] = 0 f[0][j] = 0
answer: f[a.length()][b.length()]