我有一个程序,用于查找字符串所有可能的排列组合。
#include <stdio.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 i, int n)
{
int j;
if (i == n)
printf("%s\n", a);
else
{
for (j = i; j <= n; j++)
{
swap((a+i), (a+j));
permute(a, i+1, n);
swap((a+i), (a+j)); //backtrack
}
}
}
/* Driver program to test above functions */
int main()
{
char a[] = "abcd";
permute(a, 0, 3);
getchar();
return 0;
}
我想知道是否有更好的方法(更高效)来查找所有排列,因为该算法效率为O(n^n)。
谢谢.. :-)
std::next_permutation
函数? - Mohit Jain<algorithm>
库中的std::next_permutation
函数。 - Cory Kramer