【问题标题】:Time complexity of recursive algorithm with two recursive calls具有两个递归调用的递归算法的时间复杂度
【发布时间】:2016-12-10 16:42:27
【问题描述】:

我正在尝试分析解决Generate all sequences of bits within Hamming distance t 问题的递归算法的时间复杂度。算法是这样的:

// str is the bitstring, i the current length, and changesLeft the
// desired Hamming distance (see linked question for more)
void magic(char* str, int i, int changesLeft) {
        if (changesLeft == 0) {
                // assume that this is constant
                printf("%s\n", str);
                return;
        }
        if (i < 0) return;
        // flip current bit
        str[i] = str[i] == '0' ? '1' : '0';
        magic(str, i-1, changesLeft-1);
        // or don't flip it (flip it again to undo)
        str[i] = str[i] == '0' ? '1' : '0';
        magic(str, i-1, changesLeft);
}

这个算法的时间复杂度是多少?


在这方面我觉得自己很生疏,这是我的尝试,我觉得这与事实相去甚远:

t(0) = 1
t(n) = 2t(n - 1) + c
t(n) = t(n - 1) + c
     = t(n - 2) + c + c
     = ...
     = (n - 1) * c + 1
    ~= O(n)

其中n 是位串的长度。

相关问题:12

【问题讨论】:

    标签: c++ algorithm recursion bit-manipulation time-complexity


    【解决方案1】:

    它是指数

    t(0) = 1
    t(n) = 2 t(n - 1) + c
    t(n) = 2 (2 t(n - 2) + c) + c          = 4 t (n - 2) + 3 c
         = 2 (2 (2 t(n - 3) + c) + c) + c  = 8 t (n - 3) + 7 c
         = ...
         = 2^i t(n-i) + (2^i - 1) c         [at any step i]
         = ...
         = 2^n t(0) + (2^n - 1) c          = 2^n + (2^n - 1) c
        ~= O(2^n)
    

    或者,使用 WolframAlpha:https://www.wolframalpha.com/input/?i=t(0)%3D1,+t(n)%3D2+t(n-1)+%2B+c

    它呈指数增长的原因是您的递归调用将问题大小减少了 1,但您进行了两次递归调用。您的递归调用正在形成二叉树。

    【讨论】:

    • 结果感觉是正确的 Aziz,但你能解释一下直觉吗?我的意思是你制作这个答案的方式。学人钓鱼,不要只给他鱼! :D
    • 这种求解递推关系的方法称为“伸缩”。您基本上一遍又一遍地替换函数 t(n),直到您能够确定关系中的模式(对于给定的步骤 i)。然后你就可以用 t(0) 确定最后一步,这就是解。
    • 非常感谢 Aziz,我们不应该在等式中引入changesLeft 吗?我的意思是在its iterative version, we did,它在那里被称为dist(我试图在理论上比较它们)。我知道对于给定的changesLeft,(n 选择changesLeft)次,我们将到达这行代码:printf("%s\n", str);。我发布了relevant question;如果你有时间,请看看! :)
    猜你喜欢
    • 2016-04-07
    • 1970-01-01
    • 2011-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多