下面的递归函数会打印出什么样的数字序列 如果我们以 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/