Time complexity of recursive algorithm with two recursive calls

余生长醉 提交于 2019-12-11 03:28:55

问题


I am trying to analyze the Time Complexity of a recursive algorithm that solves the Generate all sequences of bits within Hamming distance t problem. The algorithm is this:

// 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);
}

What is the time complexity of this algorithm?


I fond myself pretty rusty when it comes to this and here is my attempt, which I feel is no where near the truth:

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)

where n is the length of the bit string.

Related questions: 1, 2.


回答1:


It's exponential:

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)

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

The reason it's exponential is that your recursive calls are reducing the problem size by 1, but you're making two recursive calls. Your recursive calls are forming a binary tree.



来源:https://stackoverflow.com/questions/41077828/time-complexity-of-recursive-algorithm-with-two-recursive-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!