algorithm - 如何回答这个递归问题,它和循环之间有很大的区别吗

标签 algorithm loops recursion

下面的递归函数会打印出什么样的数字序列 如果我们以 N 赋值 1 开始它的过程?

       procedure Exercise (N)
        print the value of N;
           if (N < 3) then (apply the procedure Exercise to the
          value N + 1);
        print the value of N.

正确答案应该是 123321 但我试着自己回答,我得到了 1233

最佳答案

你忘记了最后一个“打印 N 的值语句。

假设我们用 Exercise(1) 调用它。那么这意味着它被评估为:

Exercise(1):
    print 1
    Exercise(1+1)
    print 1

Exercise(2) 调用将导致:

Exercise(2):
    print 2
    Exercise(2+1)
    print 2

Exercise(3) 调用仅产生两个 print 语句,因为 if 语句中的条件为假,因此:

Exercise(3):
    print 3
    print 3

如果我们现在执行替换,我们得到:

Exercise(1):
    print 1
        print 2
            print 3
            print 3
        print 2
    print 1

这确实会产生预期的序列。

关于algorithm - 如何回答这个递归问题,它和循环之间有很大的区别吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54237224/

相关文章:

php - 每次循环运行时更改 div id

R - 比较 R 中 2 个数据帧之间的数据

python - 如何使用递归选择字符串中的特定部分?

javascript - 递归函数进行搜索

Python:确保每个成对距离 >= 某个最小距离

python - Selenium - 网页抓取相同内容但 xpath 略有不同的多个 url

algorithm - 复杂性理论中的 O(lg(n)) * O(lg(n))

python - 尝试使用递归方法生成字符串的子集

algorithm - 计算带有附加约束的赋值

c++ - 理解Visual C++的rand()函数的算法