【问题标题】:Runtime complexity of recursive permutation function递归置换函数的运行时复杂度
【发布时间】:2020-07-25 12:36:48
【问题描述】:

我编写了这段代码,它返回所提供字符串的所有排列。现在我想计算运行时复杂度并需要帮助。

代码递归调用permutationRecursively函数N次(对于字符串的每个字符,即st),然后有两个for循环,一个循环遍历从递归调用返回的所有排列(即a它将是 ['a'] 或 ab 它将是 ['ab', 'ba'] 等等),然后是每对排列。我真的对这部分感到困惑。这个特定部分的复杂性是多少?

我假设对于所有递归调用,它将是O(N),然后对于内部循环,它将是O(A*B)。所以总数是O(N*A*B)。对吗?

def permutationRecursively(st):
    if(len(st) < 2):
        return [st]
    else:
        permutations = permutationRecursively(st[0:-1])
        newPermutations = []
        wordToInsert = st[-1]
        for permutationPair in permutations:
            for index in range(len(permutationPair)+1):
                newPermutations.append(permutationPair[0:index]+wordToInsert+permutationPair[index:])          
        return newPermutations

start_time = time.time()
permutationRecursively("abbc")
print("--- %s seconds ---" % (time.time() - start_time))

【问题讨论】:

  • 请不要接受我的回答。 @Mo.B 提供的答案是正确的答案。

标签: algorithm recursion data-structures time-complexity permutation


【解决方案1】:

您的函数首先在大小为n-1 的输入上递归调用自身。然后它遍历结果的每个元素(其中有(n-1)!),并且对于每个元素,它都执行O(n²) 工作(因为len(permutationPair)+1 的长度为n,字符串连接为O(n)

因此我们得到以下时间复杂度的递归关系T(n)

T(n) = T(n-1) + (n-1)! n²

这个关系的渐近行为如下:

T(n) ∈ Θ((n-1)! n²) = Θ(n!n)

所以,特别是T(n) ∉ O(n!)

【讨论】:

  • 不错的答案。我很高兴其他人以敏锐的眼光看待这个问题。我已要求 OP 不接受我的回答。一旦发生这种情况,我将删除它,因为这是正确的方法。
猜你喜欢
  • 2011-07-18
  • 2018-05-29
  • 2018-08-18
  • 1970-01-01
相关资源
最近更新 更多