以迭代方式编写递归代码
Writing Recursive code iteratively
我有以下递归代码,我想将其更改为迭代代码。我不确定从哪里开始,因为该函数非常复杂,在两个位置进行递归调用。以下函数的任何可能的迭代实现?
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++ 字符串中是否存在大写字符
- 为什么我的递归代码给出 sigsegv 错误?
- 以下递归代码的时间复杂度是多少?
- 弄清楚这段代码是怎么回事(递归下降案例研究)
- Fibbonaci 递归代码返回错误值,始终返回下一个数字
- 我的递归可以吗?是否有任何破坏代码的示例?
- 我的编辑距离递归代码中的字符类型有问题
- 该递归代码用于计算指数的运行时间是多少
- 递归代码快速排序
- C 递归代码迭代
- 如何确定递归代码的Big-O
- 这个递归代码有什么问题
- 跟踪此递归代码
- 以迭代方式编写递归代码
- 递归代码上的运行时错误
- 如何将递归代码更改为迭代形式
- 为什么我的递归代码会导致堆栈溢出错误
- 查找无序后继递归代码中的段错误