【问题标题】:complexity of recursive string permutation function递归字符串置换函数的复杂度
【发布时间】:2011-07-18 19:54:25
【问题描述】:

发件人:Are there any better methods to do permutation of string?

这个函数的复杂度是多少???

void permute(string elems, int mid, int end)
{
    static int count;
    if (mid == end) {
        cout << ++count << " : " << elems << endl;
        return ;
    }
    else {
    for (int i = mid; i <= end; i++) {
            swap(elems, mid, i);
            permute(elems, mid + 1, end);
            swap(elems, mid, i);
        }
    }
}

【问题讨论】:

    标签: algorithm string complexity-theory


    【解决方案1】:

    不用太深入研究您的代码,我想我可以有理由相信它的复杂性是 O(n!)。这是因为任何枚举 n 个不同元素的所有排列的有效过程都必须遍历每个排列。有n!排列,因此算法必须至少为 O(n!)。

    编辑:

    这实际上是 O(n*n!)。感谢@templatetypedef 指出这一点。

    【讨论】:

    • 我认为您忘记了打印 O(n) 个字符的 O(n!) 次,这需要 O(n x n!) 时间。
    • @templatetypedef: nn!n!
    • @MAK- O(n!) != O((n+1)!)。确实,任何 O(n!) 也是 O((n+1)!),但反之则不成立。快速证明 - (n+1)! = O((n+1)!) 很简单。现在假设 (n+1)! = O(n!);那么一定有一些 c, n0 使得对于任何 n > n0, (n+1)! n0,n
    【解决方案2】:

    忽略打印,满足的递推关系为

    T(n) = n*T(n-1) + O(n)

    如果G(n) = T(n)/n! 我们得到

    G(n) = G(n-1) + O(1/(n-1)!)

    给出G(n) = Theta(1)

    因此T(n) = Theta(n!)

    假设打印恰好发生n! 次,我们得到的时间复杂度为

    Theta(n * n!)

    【讨论】:

    • @rajyavardhan:为什么在最初的复发中有O(n) 因素?
    • 由于交换操作 - 每个操作都需要 O(1) 并且发生在一个循环中。
    • 空间复杂度是否也是二次方O(n^2),因为存储在 Set 中的唯一排列会随着初始输入越大而变得越大?
    【解决方案3】:
    long long O(int n)
    {
        if (n == 0)
            return 1;
        else 
           return 2 + n * O(n-1);
    }
    
    int main()
    {
        //do something
        O(end - mid);
    }
    

    这将计算算法的复杂度。

    实际上 O(N) 是N!!! = 1 * 3 * 6 * ... * 3N

    【讨论】:

      猜你喜欢
      • 2020-07-25
      • 2016-04-20
      • 1970-01-01
      • 2018-05-29
      • 2017-09-04
      • 2018-08-18
      相关资源
      最近更新 更多