algorithm - 转到 : longest common subsequence back tracing

标签 algorithm go dynamic-programming longest-substring

我的代码适用于计算 LCS 的长度,但我在以下链接中应用相同的代码来读取 LCS,

http://en.wikipedia.org/wiki/Longest_common_subsequence_problem

但缺少一些字符串。你能告诉我我错过了什么吗?

Google Playground 链接:http://play.golang.org/p/qnIWQqzAf5

func Back(table [][]int, str1, str2 string, i, j int) string {
  if i == 0 || j == 0 {
    return ""
  } else if str1[i] == str2[j] {
    return Back(table, str1, str2, i-1, j-1) + string(str1[i])
  } else {
    if table[i][j-1] > table[i-1][j] {
      return Back(table, str1, str2, i, j-1)
    } else {
      return Back(table, str1, str2, i-1, j)
    }
  }
}

提前致谢。

最佳答案

我认为问题在于您的索引。如果您从 0-len-1 索引您的字符串,您的表应该有行数和列数,比字符串长度大 1。看来您在计算 LCS 的长度时已经考虑到了这一点,但在返回 LCS 时却没有考虑到这一点。您的 ij 正确表示字符串的索引,但不是表的索引,它应该比 i/j 大 1。因此,您检查 0 的基本条件是错误的,因为 str1[0]str2[0] 是有效字符

所以你的代码应该是这样的:

func Back(table [][]int, str1, str2 string, i, j int) string {
  if i == -1 || j == -1 {
    return ""
  } else if str1[i] == str2[j] {
    return Back(table, str1, str2, i-1, j-1) + string(str1[i])
  } else {
    if table[i+1][j] > table[i][j+1] {
      return Back(table, str1, str2, i, j-1)
    } else {
      return Back(table, str1, str2, i-1, j)
    }
  }
}

这里是 Live Code

关于algorithm - 转到 : longest common subsequence back tracing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20156004/

相关文章:

java - 如何使用算法对未知短信进行分组?

ruby - 如何构建、排序和打印一棵树?

algorithm - CLRS 书中如何得出 BUILD_MAX_HEAP 与 O(n log n) 不渐近紧密的结论?

java - 最多 k 次买卖股票的最大利润 [递归到 DP]

algorithm - 如果在一分钟内移动到N + 1,N - 1和2 * N,如何在最短的时间内到达目标楼层?

algorithm - 最小化数组的每个元素与整数 K 的差之和

json.Unmarshal 返回空白结构

amazon-web-services - Go 中没有 API 网关的 AWS lambda 函数 URL

algorithm - 为什么字梯的动态编程解决方案不起作用?

json - 在 Go 中解码时类型检查 json 值