【问题标题】:Writing Recursive code iteratively迭代地编写递归代码
【发布时间】:2016-09-22 10:34:05
【问题描述】:

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

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

【问题讨论】:

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-04
    • 2017-12-12
    • 2014-01-16
    • 2012-07-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 1970-01-01
    相关资源
    最近更新 更多