我一直在玩这个,但是看不出明显的解决方案.我想从XinY_Go函数中删除递归.
def XinY_Go(x,y,index,slots):
if (y - index) == 1:
slots[index] = x
print slots
slots[index] = 0
return
for i in range(x+1):
slots[index] = x-i
XinY_Go(x-(x-i), y, index + 1, slots)
def XinY(x,y):
return XinY_Go(x,y,0,[0] * y)
Run Code Online (Sandbox Code Playgroud)
该函数正在计算将X弹珠放入Y槽的方法数.这是一些示例输出:
>>> xy.XinY(1,2) [1, 0] [0, 1] >>> xy.XinY(2,3) [2, 0, 0] [1, 1, 0] [1, 0, 1] [0, 2, 0] [0, 1, 1] [0, 0, 2]
我写了一个递归版本的阿克曼函数,它运行正常:
int ackermann_r(int m, int n) {
if(m == 0) {
return n + 1;
} else if(n == 0) {
return ackermann_r(m - 1, 1);
} else {
return ackermann_r(m - 1, ackermann_r(m, n - 1));
}
}
Run Code Online (Sandbox Code Playgroud)
然后我尝试迭代地重写代码:
(我不知道如何使用 malloc 使用二维数组,所以你可能会觉得代码很脏......)
int ackermann_i(int m, int n) {
int* A = (int*) malloc((m+1) * (n+1) * sizeof(int));
for(int i = 0; i <= m; i++) {
for(int j = 0; j <= n; j++) {
if(i == 0) { …Run Code Online (Sandbox Code Playgroud) 例如,在 Python 中,如果我们将列表作为数组,它会直接打印一行代码的整个数组。有没有办法,在C语言中实现同样的事情?