以迭代方式编写递归代码

Writing Recursive code iteratively

本文关键字:递归 代码 方式编 迭代      更新时间:2023-10-16

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

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;
}