【发布时间】:2016-12-12 16:49:32
【问题描述】:
我有两种算法可以解决这个问题:Generate all sequences of bits within Hamming distance t。现在我想从理论上比较它们(如果需要,我确实有时间测量)。
iterative algorithm 的复杂度为:
O((n 选择 t) * n)
其中n 是位串的长度,t 是所需的汉明距离。
recursive algorithm,到目前为止我们最好的是:
O(2^n)
但是如何比较这两个时间复杂度,而不在第二个时间复杂度中引入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);
}
【问题讨论】:
-
n choose t is n!/(t!.(nt)!) 这有最小值 1(t==0),最大值 n!/(n/2) !²(t==n/2)。
-
没有。 t==n/2 是迭代复杂度最大的地方!
-
有趣的是,没有一个回答算法在另一个位向量上使用
next_permutation。 -
最后,观察到对于小的 t,递归复杂度优于 2^n。如果 t==0,它将立即返回,如果 t=1,“翻转”分支将不再递归。另外,如果勾选
changesLeft > i并返回,如果t接近n,则可以提前返回。 -
没有@samgak(真的很抱歉造成混乱)。修复
t,假设n/2计算函数的时间复杂度,我想这样就足够了。
标签: c++ algorithm performance recursion time-complexity