下面给出自己编写的代码:
1 #include<stdio.h> 2 int P[100],A[100]; 3 void print_permutation(int n,int* P,int* A,int cur) 4 { 5 int i, j; 6 if(cur == n) 7 { 8 for(i = 0; i < n; i++) 9 printf("%d ", A[i]); 10 printf("\n"); 11 } 12 else for(i = 0; i < n; i++) 13 if(!i || P[i] != P[i-1]) 14 { 15 int c1 = 0, c2 = 0; 16 for(j = 0; j < cur; j++) if(A[j] == P[i]) c1++; 17 for(j = 0; j < n; j++) if(P[i] == P[j]) c2++; 18 if(c1 < c2) 19 { 20 A[cur] = P[i]; 21 print_permutation(n, P, A, cur+1); 22 } 23 } 24 } 25 int main() 26 { int i, n; 27 scanf("%d", &n); 28 for(i = 0; i < n; i++) 29 scanf("%d", &P[i]); 30 print_permutation(n, P, A, 0); 31 return 0; 32 }
还有一种是调用c++中stl库函数:next_permutation.
1 #include<cstdio> 2 #include<algorithm> 3 using namespace std; 4 int main() 5 { 6 int n,p[10]; 7 scanf("%d",&n); 8 for(int i=0;i<n;i++) scanf("%d",&p[i]); 9 sort(p,p+n); 10 do{ 11 for(int i=0;i,n;i++) printf("%d ",p[i]); 12 printf("\n"); 13 }while(next_permutation(p,p+n)); 14 return 0; 15 }
生成可重集的排列
时间: 2024-10-09 20:24:36