【发布时间】:2020-11-20 02:57:18
【问题描述】:
假设我们有两个长度分别为 n,m 的字符串 X,Y。 我找到了 X 和 Y 的最长公共子序列 Z。
如何证明最长公共子序列 (LCS) 的最优子结构性质?
【问题讨论】:
假设我们有两个长度分别为 n,m 的字符串 X,Y。 我找到了 X 和 Y 的最长公共子序列 Z。
如何证明最长公共子序列 (LCS) 的最优子结构性质?
【问题讨论】:
为了证明问题子结构的最优性,您需要首先定义您的state 是什么。
LCS 问题:
Strings: X, Y
X = x1x2.....xN #length=N
Y = y1y2.....yM #length=M
对于 LCS 问题,让我们将状态 D[i,j] 定义为:
D[i,j] = longest common subsequence of substrings X[1:i] and Y[1:j]
Based on our definition above, we are looking to find the value of **D[N, M]**
x[i] == y[j]
1. If the characters we are comparing are already the same, it can very well be part of the longest-common-subsequence for X[1:i] and Y[1:j].
2. The LCS might also turn-out from X[1:i-1] & Y[1:j]; OR
3. turn-out from X[1:i] & Y[1:j-1]
Thus,
D[i][j] = maxlen(D[i-1][j-1] + {X[i]}, D[i-1][j], D[i][j-1])
x[i] != y[j]
Argument follows directly from previous case:
D[i][j] = maxlen(D[i-1][j], D[i][j-1])
优化的推理来自归纳,因为我们从下到上构建最终答案D[N,M]。
【讨论】: