给定由n(n≥1)个元素组成的集合,输出该集合所有可能的排列。例如,集合{a,b,c}的所有的可能排列为{(a,b,c),(a,c,b),(b,a,c),(b,c,a),(c,a,b),(c,b,a)}。显然,给定n个元素,共有n!个可能的排列。如果给定的集合是{a,b,c,d},可以用下面给出的简单算法来产生其所有可能的排列,即{a,b,c,d}的所有可能的排列由下列的排列组成:
(1)以a开头后面跟着(b,c,d)的所有排列
(2)以b开头后面跟着(a,c,d)的所有排列
(3)以c开头后面跟着(a,b,d)的所有排列
(4)以d开头后面跟着(a,b,c)的所有排列
那么可以得到递归的全排列产生算法:
void perm(char *str,int i,int n)
{
int j,temp;
if (i == n) {
for(j = 0; j <= n; j++)
printf("%c ",str[j]);
printf("\n");
}
else{
for(j = i; j <= n; j++){
swap(str+i,str+j);
perm(str,i+1,n);
swap(str+i,str+j);
}
}
}
在C++中可以利用algorithm库中的next_permutation可以方便地获得全排列:
template <class BidirectionalIterator> bool next_permutation (BidirectionalIterator first, BidirectionalIterator last ); template <class BidirectionalIterator, class Compare> bool next_permutation (BidirectionalIterator first, BidirectionalIterator last, Compare comp); | <algorithm> |
[ACTION]Transform range to next permutation
Rearranges the elements in the range [first, last) into the lexicographically next greater permutation of elements. The comparisons of individual elements are performed using either operator< for the first version, or comp for the second.
A permutation is each one of the N! possible arrangements the elements can take (where N is the number of elements in the range). Different permutations can be ordered according on how they compare lexicographicaly to each other; The first such-sorted possible permutation (the one that would compare lexicographically smaller to all other permutations) is the one which has all its elements sorted in ascending order, and the largest has all its elements sorted in descending order.
If the function can determine the next higher permutation, it rearranges the elements as such and returns true. If that was not possible (because it is already at the largest), it rearranges the elements according to the first permutation (sorted in ascending order) and returns false.
[PARAMETERS]first, last[RETURN VALUE]true if the function could rearrange the object as a lexicographicaly greater permutation. Otherwise, the function returns false to indicate that the arrangement is not greater than the previous, but the lowest possible (sorted in ascending order).
测试程序:
void main()
{
char s[] = "abcd";
//perm(s,0,3);
do
{
for(int i = 0; i < 4; i++)
printf("%c ",s[i]);
printf("\n");
}while(next_permutation(s,s+4));
}
测试输出:
a b c d
a b d c
a c b d
a c d b
a d b c
a d c b
b a c d
b a d c
b c a d
b c d a
b d a c
b d c a
c a b d
c a d b
c b a d
c b d a
c d a b
c d b a
d a b c
d a c b
d b a c
d b c a
d c a b
d c b a
若修改输入参数
char s[] = "bcad";
则输出为:
b c a d
b c d a
b d a c
b d c a
c a b d
c a d b
c b a d
c b d a
c d a b
c d b a
d a b c
d a c b
d b a c
d b c a
d c a b
d c b a