单词置换生成器

时间:2018-02-13 21:56:37

标签: c

我找到了几个我想要做的例子,但当然没有一个完全符合我的要求。

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

*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;
}

1 个答案:

答案 0 :(得分:1)

而不是

char str[] = "one two three";

尝试从

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

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