【发布时间】:2020-09-25 03:50:13
【问题描述】:
我写了一个简单的算法来返回一个字符串所有可能排列的列表,如下:
def get_permutations(sequence):
'''
Enumerate all permutations of a given string
sequence (string): an arbitrary string to permute. Assume that it is a
non-empty string.
Returns: a list of all permutations of sequence
'''
if len(sequence) <= 1:
return list(sequence)
else:
return_list = get_permutations(sequence[1:])
new_list = []
for e in return_list:
for pos in range(len(e) + 1):
new_list.append(e[:pos] + sequence[0] + e[pos:])
return new_list
从这段代码中,我看到了 O(n* n!) 的时间复杂度,O(n!) 是“return_list”中元素“e”数量的增加趋势,并且有一个嵌套循环随着每个新的递归线性增加,所以据我了解,O(n)。结论是该算法作为一个整体具有 O(n*n!) 复杂度。
然而,在寻找类似的解决方案时,我发现很多线程说这种算法的最佳情况应该只有 O(n!),所以我的问题是:
是我在复杂性分析中遗漏了什么,还是我的代码不是最优的?如果不是,我该如何正确纠正它?
【问题讨论】:
标签: python algorithm performance time-complexity permutation