我正在努力从像 ABCD 这样的代码生成所有组合,例如,这个 1 * 2 * 3 * 4 有 24 种组合。
我有这个功能:
static char *combi_switch(char *code, int i)
{
char *combi;
int j;
int k;
int l;
int s;
combi = (char *)malloc(sizeof(char) * ft_strlen(code) + 1);
ft_strcpy(combi, code);
k = i;
l = i;
j = ft_strlen(code) - 1;
if (i == j)
{
printf("%s\n", combi);
return (combi);
}
while (l <= j)
{
s = combi[i];
combi_switch(map, combi, k + 1, stock);
while (i < j)
{
combi[i] = combi[i + 1];
i++;
}
i = k;
combi[j] = s;
l++;
}
free(combi);
return (NULL);
}
这个调用的ini:
char *combi_mix(char *code)
{
combi_switch(code, 0);
return (NULL);
}
ft_strlen && ft_strcpy 与 libc 包含的内容相同。
因此,对于此函数,如果 code = "ABCD",printf
将说明返回的 24 种组合。
我将所有返回存储在 char ** 或链接列表中。
- 有没有办法存储我
printf
的所有组合? - 在递归函数中使用“while”循环是否存在问题?
这是我项目的最后一个功能之一,所以如果您能帮助我,非常感谢!
最佳答案
不,任何类型的函数中的任何类型的控制结构都没有任何特殊问题。使用 while
或其他。现在,一旦我们把它从系统中取出来,我们就集中精力讨论重要的问题。如何累积函数的结果而不是打印它们?函数实际计算什么并不重要,重要的是它是递归的并且每次调用都会打印一些东西。我们想要收集而不是打印。
首先,函数应该返回一些东西。您当前的函数返回一个 char*
但从未使用过它。您的新函数应该返回您想要的值,即集合。
typedef struct {
/* whatever */
} string_collection;
我们没有指定集合中包含哪些内容。它可能是一个链接列表,或者一个动态数组及其长度,或者其他什么。您决定想要什么样的收藏。
现在您需要几个函数:
string_collection* create_empty_collection();
void add_element (string_collection* c, const char* s);
void move_elements (string_collection* c1,
string_collection* c2); // moves all elements from c2 to c1, leaving c2 empty
void destroy_collection (string_collection* c);
这些函数修改它们的参数。这些只是示例签名。如果您愿意,您可以选择完全不可变的接口(interface):
string_collection* add_element (const string_collection* c, const char* s);
string_collection* concatenate (const string_collection* c1,
const string_collection* c2); //etc
在此变体中,您可以创建一个全新的集合,而无需触及现有集合。每种风格都有其自己的位置;使用任何对你有用的东西。
现在修改函数就很简单了:
string_collection* your_function (whatever parameters)
{
// First, need a collection to return
string_collection* coll = create_empty_collection();
// whatever
// whatever
// ATTN: old code was: printf ("%s", something), now do this:
add_elememt (coll, something);
// whatever
// whatever
// ATTN: old code was: your_function(whatever parameters), now do this:
string_collection* new_coll = your_function(whatever parameters);
move_elements (coll, new_coll);
destroy_collection (new_coll);
// whatever
// whatever
// ATTN: old code was: return something, now do this:
return coll;
}
当您调用函数时,您现在会执行以下操作:
string_collection* coll = your_function (whatever parameters)'
// do something with the collection
destroy_collection (coll);
这里我们刚刚学会了累积递归函数结果。太棒了!
与此相关的是,您的函数 malloc
每次调用时都会生成一个字符串,但看不到 free
。这很糟糕(内存泄漏)。请添加
free (combi);
在适当的情况下。在您的情况下,这意味着在任何 return
语句之前。 (最好在函数末尾使用单个 return
语句,而不是分散在整个函数体内的多个语句;这就是这样做的原因之一)。
关于c - 如何存储递归函数的多个返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34903687/