#define _CRT_SECURE_NO_DEPRECATE #include<iostream> #include<algorithm> #include<fstream> using namespace std; const int maxn = 50; int a[maxn]; bool vis[maxn]; void permutation(int *a,int curr,int n){ if (curr == n){ for (int i = 0; i < n; i++) printf("%d ", a[i]); printf(" "); return; } for (int i = 1; i <= n; i++){ if (!vis[i]){ vis[i] = 1; //标记访问 a[curr] = i; permutation(a, curr + 1, n); vis[i] = 0; //撤销标志 } } } /*STL函数next_permutation是按照字典序求下一个排列,可以处理元素重复的情况。 ---*/ void permutation(int*a,int n){ sort(a, a + n); do{ for (int i = 0; i < n; i++)printf("%d ", a[i]); printf(" "); } while (next_permutation(a, a + n)); } int main(){ int n; int p[5] = { 2, 5, 1, 7, 2 }; permutation(p, 5); while (~scanf("%d", &n)){ memset(vis,0, sizeof(vis)); permutation(a,0,n); } return 0; }