题目描述
设R=(1, 2, .., n),计算R的全排列。 分治法求解全排列的算法思想: 设R=(1, 2, .., n)的全排列为P(R), 若R=(),则P()=(); 否则,P(R)={(1)P(2, 3, .., n),(2)P(1, 3, .., n), (3)P(2, 1, .., n), .., (n)P(2, .., n-1, 1)}; 同样地,P(2, 3, .., n)={(2){3, 4, .., n}, (3){2, 4, .., n}, .., (n){3, .., n-1, 2}}
输入
输入为一组不大于7的整数。
输出
对每个输入的整数n,用分治法计算并输出1..n的全排列。
样例输入
123
样例输出
1 1 2 2 1 1 2 3 1 3 2 2 1 3 2 3 1 3 2 1 3 1 2
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<malloc.h>
using namespace std;
void perm(int a[],int k,int m){
int i;
if(k==m){
for(i=0;i<=m;i++)
printf("%d ",a[i]);
printf("\n");
return;
}
else{
for(i=k;i<=m;i++){
swap(a[i],a[k]);
perm(a,k+1,m);
swap(a[i],a[k]);
}
}
}
int main(){
int n;
int a[100];
while(~scanf("%d",&n)){
int i;
for(i=0;i<n;i++){
a[i]=i+1;
}
perm(a,0,n-1);
}
return 0;
}
来源:CSDN
作者:tzuhsiao
链接:https://blog.csdn.net/qq_32126633/article/details/52916967