【发布时间】: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 是位串的长度。
【问题讨论】:
标签: c++ algorithm recursion bit-manipulation time-complexity