【问题标题】:Optimal Substructure Property最优子结构属性
【发布时间】:2020-11-20 02:57:18
【问题描述】:

假设我们有两个长度分别为 n,m 的字符串 X,Y。 我找到了 X 和 Y 的最长公共子序列 Z。

如何证明最长公共子序列 (LCS) 的最优子结构性质?

【问题讨论】:

标签: algorithm lcs


【解决方案1】:

为了证明问题子结构的最优性,您需要首先定义您的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]**

提出递归关系(D[i,j]):

案例一:

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])

案例2:

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]

【讨论】:

    猜你喜欢
    • 2014-03-30
    • 1970-01-01
    • 2014-12-13
    • 1970-01-01
    • 2016-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多