【发布时间】:2019-03-21 07:04:34
【问题描述】:
我正在浏览一些算法帖子。在审查时,我怀疑为什么我们在返回最终解决方案时在下面的代码中添加了 1。
import sys
# Recursive function to find minimum
# number of insertions
def findMinInsertions(str, l, h):
# Base Cases
if (l > h):
return sys.maxsize
if (l == h):
return 0
if (l == h - 1):
return 0 if(str[l] == str[h]) else 1
# Check if the first and last characters are
# same. On the basis of the comparison result,
# decide which subrpoblem(s) to call
if(str[l] == str[h]):
return findMinInsertions(str, l + 1, h - 1)
else:
**return (min(findMinInsertions(str, l, h - 1),
findMinInsertions(str, l + 1, h)) + 1)**
# Driver Code
if __name__ == "__main__":
str = "abc"
print(findMinInsertions(str, 0, len(str) - 1))
【问题讨论】:
-
l和h参数似乎是字符串str的索引。您需要添加1才能到达 下一个 字符。 -
我已经编辑了帖子,请再次查看@Someprogrammerdude。为什么我们在return语句的末尾加了1 return (min(findMinInsertions(str, l, h - 1),findMinInsertions(str, l + 1, h)) + 1)
-
这个程序在做什么,在我看来像加了 1,因为当前执行的递归应该算作 1。就像如果 str[l] != str[h],一个操作需要在将当前问题简化为子问题之前,将其计为 1。
-
此算法用于查找字符串中的最小插入次数以使其成为回文。
标签: python algorithm dynamic-programming insertion-sort