【发布时间】:2016-02-18 20:04:46
【问题描述】:
我讨厌在这里发帖寻求家庭作业帮助,但我已经用尽了我的能力。在用 C 语言编写一个简单的递归函数时,我遇到了 Stack Overflow(至少在 Java 中就是这样)问题。
我需要 n 个数字的每个 r 排列,并且我认为最好的方法是以 n 为底数到长度 r。
它适用于较小数量的数字,但最高的情况(n=10,r=6)最终会耗尽内存。我可以很容易地迭代地编写它,但它需要递归。这是我到目前为止所拥有的:
int permute(int *tempArray, int amtNums, int goalLength, int totalMatches) {
totalMatches += 1; //Temporary, will be replaced by a function later
printArray(tempArray, goalLength);
tempArray[0]++;
int j = 0;
while(tempArray[j] >= amtNums) {
tempArray[j+1]++;
tempArray[j] = 0;
j++;
}
if(j+1 > goalLength) return totalMatches;
return permute(tempArray, amtNums, goalLength, totalMatches);
}
在最大情况下被称为permute((int*)calloc(numSlots, sizeof(int)), 10, 6, 0);,n=10 r=6
我应该注意:计数并不完全直观,它有点倒退,但会生成我想要的所有数字组合。举个例子:n=4, r=3
0 0 0
1 0 0
2 0 0
3 0 0
0 1 0
1 1 0
2 1 0
3 1 0
.....
0 2 3
1 2 3
2 2 3
3 2 3
0 3 3
1 3 3
2 3 3
3 3 3
【问题讨论】:
-
虽然这不是堆栈溢出的原因,但千万不要将
calloc作为参数传递,你需要检查他的返回。 -
@AlterMann 我实际上并没有传递 calloc,我只是把它放在了问题中,所以我不必在问题中占用更多空间,将其视为伪代码
-
@gsamaras 它适用于不需要那么多递归的较小情况
-
@Duck:提示:你的调用栈不应该超过
ndeep。 -
@MooingDuck 我知道这是最好的方法,我只是不知道该怎么做。