c++ - 尝试比较递归和迭代算法

标签 c++ algorithm performance recursion time-complexity

我有两个算法可以解决这个问题:Generate all sequences of bits within Hamming distance t .现在我想从理论上比较它们(如果需要,我确实有时间测量)。

iterative algorithm复杂度为:

O((n choose 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);
}

最佳答案

递归算法是O((n choose t) * n)同样,通过对每个打印组合收取打印时整个调用堆栈的成本的分析。我们可以这样做是因为每次调用 magic (除了两个 O(1) 叶调用,其中 i < 0 ,我们可以很容易地取消)打印一些东西。

如果您将打印分配给它的真实成本,那么这个界限是最好的。否则,我很确定这两种分析都可以收紧到 O(n choose t)不包括 t > 0 的打印, 在 Knuth 4A 中有详细信息。

关于c++ - 尝试比较递归和迭代算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41105621/

相关文章:

performance - 是什么导致*中等*数量的项目的性能出现这种奇怪的下降?

c++ - 尝试在 map 中查找元素时出错

c++ - 使用 dOxygen 记录具有指定指针的 typedef 结构?

vb.net - 使用光线转换算法对具有纬度/经度坐标的多边形中的点进行测试

javascript - 使用过滤,优先级和最小循环将数组转换为对象

即使使用主索引并且良好的 EXPLAIN 计划,MySQL 查询也很慢

java - 为什么 Java 排序优于原语计数排序

c++ - 在 C++ 中, 'Node' 是一个类, 'node' 是 'Node' 的实例。为什么 "*node = nullptr "是错误的,而 "*node = NULL"是正确的?

c++ - 如何调用 header 包含的函数?

algorithm - 如何计算三角形索引的循环顺序?