gpt4 book ai didi

c - 单词排列生成器

转载 作者:行者123 更新时间:2023-11-30 14:50:48 26 4
gpt4 key购买 nike

我找到了几个我想做的例子,但当然没有一个完全按照我想要的方式工作。

我正在尝试修改以下程序以显示一串单词的所有可能组合。因此,例如:

*str = "one two"; // would be:
one two
two one

*str = "one two three"; // would be:
one two three
one three two

two one three
two three one

three one two
three two one

等等..

这是我正在处理的内容,它也会产生重复项,这是我不想要的。

#include <stdio.h>
#include <string.h>

/* Function to swap values at two pointers */
void swap(char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}

/* Function to print permutations of string
This function takes three parameters:
1. String
2. Starting index of the string
3. Ending index of the string. */
void permute(char *a, int l, int r)
{
int i;
if (l == r)
printf("%s\n", a);
else
{
for (i = l; i <= r; i++)
{
swap((a+l), (a+i));
permute(a, l+1, r);
swap((a+l), (a+i)); //backtrack
}
}
}

/* Driver program to test above functions */
int main()
{
char str[] = "one two three";
int n = strlen(str);
permute(str, 0, n-1);
return 0;
}

最佳答案

而不是

char str[] = "one two three";

尝试从

开始
char *strs[3];
strs[0] = "one";
strs[1] = "two";
strs[2] = "three";

然后修改您现有的算法以使用它。

关于c - 单词排列生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48776323/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com