插入法:
对于全排列的求解,第一个想到的肯定是通过递归的解法。例如对于数列p(n)={1,2,3,…,n},从中间取出一个数比如1,剩下的只需要求出p(n-1)的全排列,然后依次把1加入p(n-1)的全排列中。对于全排列也有2中方法:
将取出的数(例子中是1),依次插入到p(n-1)的全排列的不同位置上。在这里称之为插入法。
首元素依次和后续的元素交换,然后求首元素之后的子序列的全排列。这里称之为首元素固定法。
相信对于2个方法的描述,大家应该还是比较模糊的。没关系后续将会详细讲解。
#include<iostream>
using namespace std;
//交换
void swap(int &a , int &b)
{
int temp;
temp = a;
a = b;
b = temp;
}
//全排列递归算法
void Perm(int list[] , int k ,int m)
{
//list 数组存放排列的数,K表示层 代表第几个数,m表示数组的长度
if(k==m)
{
//K==m 表示到达最后一个数,不能再交换,最终的排列的数需要输出;
for(int i=0 ;i<=m ;i++)
cout<<list[i];
cout<<endl;
}
else{
for(int i=k;i<=m;i++)
{
swap(list[i],list[k]);
Perm(list,k+1,m);
swap(list[i] , list[k]);
}
}
}
int main(void)
{
int a[]={1,2,3};
int m=2;
Perm(a,0,2);
/*
123
132
213
231
321
312
*/
}
字典序法
/*
问题 A: 全排列
题目描述
排列与组合是常用的数学方法。
先给一个正整数 ( 1 < = n < = 10 )
例如n=3,所有组合,并且按字典序输出:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
输入
输入一个整数n( 1<=n<=10)
输出
输出所有全排列
每个全排列一行,相邻两个数用空格隔开(最后一个数后面没有空格)
样例输入
3
样例输出
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
*/
#include <iostream>
#include <algorithm>
using namespace std;
void show(int a[],int len){
for(int i = 0; i < len - 1; i++){
printf("%d ", a[i]);
}
printf("%d\n",a[len-1]);
}
int hash_map[10] = {0}; //hash数组用来标记哪些数字已经被使用过
int b[10] = {0};
int j = 0;
void my_next_permutation(int a[],int len){
for(int i = 0; i < len; i++){
for(;hash_map[i] == 1;i++); //始终从小到大使用 没使用过的数字
if(i != len){
hash_map[i] = 1;
b[j++] = a[i];
if(j == len) show(b,len);
my_next_permutation(a,len);
j--;
hash_map[i] = 0;
}
}
}
int main(){
int a[10]={1,2,3,4,5,6,7,8,9,10},n;
while(cin >> n){
my_next_permutation(a,n);
}
return 0;
}
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
string str;
cin >> str;
sort(str.begin(),str.end());
while (next_permutation(str.begin(), str.end()))
cout << str << endl;
return 0;
}