具有两个递归调用的递归算法的时间复杂度

时间:2016-12-10 16:42:27

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

我正在尝试分析解决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

1 个答案:

答案 0 :(得分:5)

指数

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,但是你正在进行两次递归调用。您的递归调用正在形成二叉树。