【发布时间】:2015-06-18 17:14:54
【问题描述】:
我有以下程序用于查找字符串的所有可能排列。
#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? -
我假设您使用的是 C,而不是 C++(尽管有额外的标记),否则您可以使用来自
<algorithm>的std::next_permutation -
如果您实际使用的是 C 而不是 C++,您可以将代码 here 改编为 C 代码。这篇文章是你将如何实现 next_permutation 函数。
标签: c++ c arrays string algorithm