ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

金山云笔试题:AKM函数

2019-09-29 22:51:50  阅读:421  来源: 互联网

标签:金山 peek sy sx int 笔试 pop AKM push


1. 题目描述

/**
阿克曼(Ackmann)函数

【题目描述】
阿克曼(Ackmann)函数A(m,n)中,m,n定义域是非负整数(m<=3,n<=10),函数值定义为:
akm(m,n) = n+1;         (m=0时)
akm(m,n) = akm(m-1,1);  (m>0,n=0时)
akm(m,n) = akm(m-1,akm(m, n-1)); (m,n>0时)

【输入】输入m和n。

【输出】函数值。

【输入样例】2 3
【输出样例】9
*/

写出递归与非递归算法,并输出调用过程。

 

2. 代码实现递归和非递归

import java.util.Stack;
 
public class Main2 {
    public static void main( String[] args ) {
        System.out.println(AkmRecur(2, 3));
        System.out.println(AkmNonRecur(2, 3));
    }
    //递归
    public static int AkmRecur(int m, int n)    {
        if (m == 0)
            return n + 1;
        else if (n == 0)
            return AkmRecur(m - 1, 1);
        else
            return AkmRecur(m - 1, AkmRecur(m, n - 1));
    }
    //非递归
    public static int AkmNonRecur(int m, int n)    {
        Stack<Integer> sx = new Stack<Integer>();
        Stack<Integer> sy = new Stack<Integer>();
        int x = 0;
        int y = 0;
        sx.push(m);
        sy.push(n);
        while ((!sx.empty()) && (!sy.empty())) {
             if (sx.peek() != 0 && sy.peek() == 0) {
                     x = sx.peek();
                     y = sy.peek();
                     sx.pop();
                     sy.pop();
                     sx.push(x-1);
                     sy.push(1);
             }else if (sx.peek() != 0 && sy.peek() != 0) {
                     while (sx.peek()!= 0 &&sy.peek()!= 0) {
                         x = sx.peek();
                         y = sy.peek()-1;
                         sx.pop();
                         sy.pop();
                         sx.push(x-1);
                         sy.push(-1);
                         sx.push(x);
                         sy.push(y);
                     }
             } else {
                 y = sy.peek();
                 sx.pop();
                 if (sx.empty()){
                     return y + 1;
                 } else {
                     sy.pop();
                     sy.pop();
                     sy.push(y+1);
                 }
             }
        }
        return -1;
    }
}

 

标签:金山,peek,sy,sx,int,笔试,pop,AKM,push
来源: https://www.cnblogs.com/haimishasha/p/11610405.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有