How to rewrite Ackermann function in non-recursive style?

前端 未结 6 1275
生来不讨喜
生来不讨喜 2020-12-05 14:42

I have function

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 re

6条回答
  •  没有蜡笔的小新
    2020-12-05 15:28

    Not quite O(1) but definitely non-recursive.

    public static int itFunc(int m, int n){
        Stack s = new Stack;
        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;
    }
    

提交回复
热议问题