原文地址:Write a program to print all permutations of a given string
排列,也叫“排列数”或者“order”(这个咋译?),它是一个有序的列表S一对一下相关的。一个长度为n的字符串有n!种排序。
下面是字符串“ABC”的排列:
ABC ACB BAC BCA CBA CAB
这里有一个基本的回溯方法可作为答案。
// C program to print all permutations with duplicates allowed
#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[] = "ABC";
int n = strlen(str);
permute(str, 0, n-1);
return 0;
}
输出:
ABC
ACB
BAC
BCA
CBA
CAB
算法范式(Paradigm):回溯
时间复杂度: O(n*n!)。注意,这里需要O(n)的时间来打印n!个排列。
注意:如果输入字符串中有重复字符的话,上述方法会打印出相同的排列。如果输入字符串中有相同的字符,但是输出的排列中没有相同的排列,这种问题怎么解决,请看下面的链接: