c++ - 迭代地编写递归代码

标签 c++ recursion iteration dynamic-programming tail-recursion

我有以下递归代码,我想将其更改为迭代代码。我不确定从哪里开始,因为函数非常复杂,在两个位置进行递归调用。以下函数的任何可能的迭代实现?

int ncip(int dim, double R){
    int n, r = (int)floor(R);

    if (dim == 1)
        return 1 + 2*r; 
    n = ncip(dim-1, R); // last coord 0

    for (int i=1; i<=r; ++i){
        n += 2*ncip(dim-1, sqrt(R*R - i*i) ); // last coord +- i
    }

    return n;
}

最佳答案

一种常见的方法是为函数调用使用堆栈。一个简单的实现如下,您可以对其进行一些优化

int ncip(int dim, double R){
    typedef pair<int, double> data; // ties parameters into one unit

    stack<data> s;
    s.push(make_pair(dim,R)); // push the first set of parameters
    int n = 0;

    while(false == s.empty()) { // do the loop until stack is depleted
        auto item = s.top(); // get the top item and pop it after
        s.pop();
        int r = static_cast<int>(floor(item.second));

        if (item.first == 1) {
            n += 1 + 2*r; 
        } else {
            s.push(make_pair(item.first-1,item.second));

            for (int i = 1; i <= r; ++i){
                // since you have a multiplier 2 we push the same parameters twice
                s.push(make_pair(item.first-1, sqrt(item.second*item.second - i*i) ));
                s.push(make_pair(item.first-1, sqrt(item.second*item.second - i*i) ));
            }
        }
    }
    return n;
}

关于c++ - 迭代地编写递归代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37426674/

相关文章:

c++ - 初始化列表和基于范围的函数

c++ - 处理解码时改变的分辨率?

C++ 字符串\vector 初始化

c++ - 未定义的 vtable 引用

递归计数直到某个数字递减并备份

java - 斐波那契使用递归从用户在 Java CLI 中给出的两个任意数开始

javascript - 连接 2 个相似对象 javaScript 的所有属性

java - 使用递归时如何保持一致性?

python - 计算迭代操作百分比的最佳方法是什么?

javascript - 如何遍历树并过滤javascript中的匹配节点?