本文介绍了如何以非递归方式重写Ackermann函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有功能
public static int func(int M,int N){
if(M == 0 || N == 0) return M+N+1;
return func(M-1, func(M, N-1));
}
如何以非递归方式重写它?
也许,它实现了一些算法吗?
How to rewrite it in non-recursive style ?Maybe, is it implementation some algorithm?
推荐答案
不完全是O(1)但绝对是非递归的。
Not quite O(1) but definitely non-recursive.
public static int itFunc(int m, int n){
Stack<Integer> s = new Stack<Integer>;
s.add(m);
while(!s.isEmpty()){
m=s.pop();
if(m==0||n==0)
n+=m+1;
else{
s.add(--m);
s.add(++m);
n--;
}
}
return n;
}
这篇关于如何以非递归方式重写Ackermann函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!