如何以排序顺序生成数组的所有排列? [英] How to generate all permutations of an array in sorted order?
问题描述
我有一个数组,用户可以插入一个字符串。
我有这个代码:
int main(){
char anagrama [13];
cin>> agram
for(int j = 0; j< strlen(anagrama); j ++){
cout< anagrama [j];
for(int k = 0; k if(j!= k)
cout< agram
}
cout<< endl;
}
}
问题是我需要所有
例如,如果用户写: abc
,输出必须为:
abc
acb
bac
bca
cab
cba
并且我的代码不显示所有排列,
我需要做一个没有实现的函数的实现。
我想用递归函数,但我不知道如何。
这是一个例子:
http://www.disfrutalasmatematicas.com/combinatoria/combinaciones-permutaciones-calculadora.html无重复和排序
在C ++中,您可以使用 std :: next_permutation
逐个进行排列。首次调用 std :: next_permutation
之前,您需要按字母顺序对字符进行排序:
cin>> anagrama;
int len = strlen(anagrama);
sort(anagrama,anagrama + len);
do {
cout<< anagrama endl;
} while(next_permutation(anagrama,anagrama + len));
这是一个演示ideone 。
如果您必须自行实现排列,您可以借用 next_permutation
的源代码,或者选择一种更简单的递归实现置换算法的方法。
I have an array, and the user can insert a string.
And I have this code:
int main(){
char anagrama[13];
cin >> anagrama;
for(int j = 0; j < strlen(anagrama); j++){
cout << anagrama[j];
for(int k = 0; k < strlen(anagrama); k++){
if(j != k)
cout << anagrama[k];
}
cout << endl;
}
}
The problem is that I need all permutations of the string in sorted order.
For example if the user write: abc
, the output must to be:
abc
acb
bac
bca
cab
cba
and my code doesn't show all permutations, and not sorted
Can you help me?
I need do the implementation without a function already implemented.
I think with a recursive function, but I do not know how.
This is an example: http://www.disfrutalasmatematicas.com/combinatoria/combinaciones-permutaciones-calculadora.html without repetition and sorted
In C++ you can use std::next_permutation
to go through permutations one by one. You need to sort the characters alphabetically before calling std::next_permutation
for the first time:
cin>>anagrama;
int len = strlen(anagrama);
sort(anagrama, anagrama+len);
do {
cout << anagrama << endl;
} while (next_permutation(anagrama, anagrama+len));
Here is a demo on ideone.
If you must implement permutations yourself, you could borrow the source code of next_permutation
, or choose a simpler way of implementing a permutation algorithm recursively.
这篇关于如何以排序顺序生成数组的所有排列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!