gsa*_*ras 2 c++ algorithm recursion bit-manipulation time-complexity
我试图分析一个递归算法的时间复杂度,该算法解决了汉明距离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);
}
Run Code Online (Sandbox Code Playgroud)
这个算法的时间复杂度是多少?
在谈到这一点时,我喜欢自己很生疏,这是我的尝试,我觉得这不是真相:
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)
Run Code Online (Sandbox Code Playgroud)
n位串的长度在哪里.
这是指数级的:
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)
Run Code Online (Sandbox Code Playgroud)
或者,使用WolframAlpha:https://www.wolframalpha.com/input/ ? i = t(0)%3D1,+ t(n)%3D2 + t(n-1)+%2B + c
它是指数的原因是你的递归调用将问题大小减少了1,但你正在进行两次递归调用.您的递归调用正在形成二叉树.