1.STL库中的库中的库中的库中的next_permutation()函数函数函数函数
字典序:存在相同元素,不会重复。
#include <iostream>
#include <algorithm>#include <string>
using namespace std;
int main()
{
string str;
cin >> str;
sort(str.begin(), str.end());//必须先排序
cout << str << endl;
while (next_permutation(str.begin(), str.end()))
{
cout << str << endl;
}
system("pause");
return 0;
}
-----------------------------------------------
2.从第m个元素到第n个元素的全排列的算法:
存在相同元素,会重复。
#include <algorithm>
#include <string>
using namespace std;
int g_iCount = 0;
void Permutation(int A[], int m, int n)
{
int i, temp;
if(m == n)
{
for(i = 0;i<n;i++)
{
if(i != n-1)
printf("%d ",A[i]); //有加空格
else
printf("%d", A[i]); //没加空格
}//直接输出,因为前n-1个数已经确定,递归到只有1个数。
printf("\n");//一组输出完毕
g_iCount++;
return;
}
else
{
for(int i=m;i<n;i++) /*进入for循环,对应第一步,注意此处是m,而不是0,因为是递归调用,对应的是第m个元素到第n个元素的全排列。*/
{
temp = A[m];
A[m] = A[i];
A[i] = temp; //交换,对应第二步
Permutation(A,m+1,n); //递归调用,对应三至五步
temp = A[m];
A[m] = A[i];
A[i] = temp; //交换,变回原来的数组
}
}
}
void Full_Array(int A[],int n)
{
Permutation(A, 0,n);//第0个元素到第n个元素的全排列
printf("\n%d", g_iCount);//组合个数
}
int main()
{
int a[10] = {1, 2, 3, 4, 5};
Full_Array(a, 5);
system("pause");
return 0;
}

1729

被折叠的 条评论
为什么被折叠?



